Write to and read from a text file in Php
Tagged:

The function write_log below writes the contents of an array $contentstowrite to a text file log.txt (The array and filename can be modified as required). The content to write should be an array or else it displays an error.


// Writing to a text file
function write_log($filename,$towrite){
if(!is_array($towrite)){
echo "Supplied content to write is not an array, a valid array is required to write";
die();
}

$fw=fopen($filename,"a+");
/* Second parameter description for the above function fopen
w+ --> opens a file and creates new contents replacing old. If the file does not exist, attempts to create it.
a+ --> opens a file and appends to it. If the file does not exist, attempts to create it.
*/
foreach($towrite as $key=>$val){
fwrite($fw,$val."\n");
}

echo "Successfully written to log";
fclose($fw); // closes an open file pointer $fw
}

$contentstowrite = array('dell','apple','hp','vaio');
write_log('log.txt',$contentstowrite);

This function read_log below is used to read the contents of the file log.txt (can be modified as required) and display it.


// Reading from a text file
function read_log($filename){
$fd=fopen($filename,"r"); // opens a file for reading only
$out = "

Brand

";

// If the file cannot be read or doesn't exist,the function fopen returns FALSE
if($fd){
// FALSE from fopen will issue warning and result in infinite loop when calling the function feof
// So to avoid the infinite loop and filling of the error logs, we call feof only if $fd returns TRUE
while(!feof($fd)) {
$out .= "

";
$line = fgets($fd,4096); // Gets a line from the file
// The second optional parameter 4096 is the line length of a file to be read
// Reading ends after this length, we have to increase it if the file has larger lines to be read.
$out .= $line."

";
}
fclose($fd); // closes an open file pointer $fd
}

return $out;
}
echo read_log('log.txt');

The final output of the whole code is displayed below. I have set the fopen mode to append while writing to a file. Hence, everytime we run this code, the same contents are appended to the log over and over again.


Successfully written to log
Brands
--------------------
dell
apple
hp
vaio