Write to and read from file in PHP
Description
The following code shows how to write to and read from file.
Example
<?php/*from w w w.j ava2 s . c o m*/
// open file for writing
$filename = "test.txt";
if(!($myFile = fopen($filename, "w")))
{
print("Error: ");
print("'$filename' could not be created\n");
exit;
}
//write some lines to the file
fputs($myFile, "Save this line for later\n");
fputs($myFile, "Save this line too\n");
//close the file
fclose($myFile);
// open file for reading
if(!($myFile = fopen($filename, "r")))
{
print("Error:");
print("'$filename' could not be read\n");
exit;
}
while(!feof($myFile))
{
//read a line from the file
$myLine = fgets($myFile, 255);
print("$myLine<br>\n");
}
//close the file
fclose($myFile);
?>
The code above generates the following result.