Home > Article > Backend Development > PHP reads file content and writes data to file_PHP tutorial
PHP reads file contents and writes data to files. Here we mainly talk about writing data to files line by line, and reading the contents of files line by line.
php tutorial reading file content and writing data to file
Here we mainly talk about writing data to the file line by line, and reading the contents of the file line by line.
*/
$fp = fopen($_server['document_root']."/../data/info.dat",'r');
if(!$fp)
{
echo "error: Error opening file, please check whether the directory is correct, or try again later!";
exit;
}while(!feof($fp))
{
$line = fgets($fp);
echo $line;
echo '
';
}
fclose($fp);
//Write file
$file = "data.txt";
$content = "Content titlernwww.bkjia.comrnSecond line of content"; //Content to be writtenif(!$fp = fopen($file,'a')) //When opening the file $file, use the append mode, and the file pointer will be at the beginning of the file
{
echo "Failed to open file $file!";
exit;
}if(fwrite($fp,$content) === false) //Write content to file
{
echo "Failed to write file!";
exit;
}echo "Writing file successfully!";
fclose($fp);