How to read and write from a file in php ?

Want to write some data to a text file and read the value.This article will demonstrate to you by an example how to write to a file and also an example to read from a file in PHP.The file will be written at a specified folder in your web hosting server and also be read from it.

Writing to a file php example

$myfile="/home/username/public_html/new.txt";
$file_name= $myfile;
$file_handle= fopen($file_name,"a");
//places file pointer at end of file ,file open for writing,if a+ then both reading writing
$output_string = "This is a "."n";
$output_string.= "multiple line"."n";
$output_string.= "text with newline"."n";
$output_string.= "at end of each line"."n";
fwrite($file_handle,$output_string);
fclose($file_handle);

Reading a file in php example

$myfile="/home/username/public_html/new.txt";
$file_name= $myfile;
$file_handle= fopen($file_name,"r");//places file pointer at begining of file ,file open for reading
$file_contents_string = file_get_contents($file_name);
$pieces = explode("n", $file_contents_string);
foreach ($pieces as $value)
{
echo $value."/n";
}


That is all.

If you liked this article please do leave a reply and share it with friends.

Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.