Tuesday, January 22, 2013

PHP - read and write text file


Below are the sample codes to read and write text file using PHP

Read content of a file

<?php
//file name
$filename = "textFile.txt";

//open the file with Read only Mode. Starts at the beginning of the file.
$file = fopen($filename, "r");

//all content the file
$contents = fread($file, filesize($filename));

//close the file
fclose($file);

//print the content
echo $contents;
?>


Read content of a file line by line

<?php
//file name
$filename = "textFile.txt";

//open the file with Read only Mode. Starts at the beginning of the file.
$file = fopen($filename, "r");

//loop the file until the end is reached
while(!feof($file))
{
echo fgets($file)."<br>";
}

//close the file
fclose($file);
?>



Write file

<?php
//file name
$filename = "newFile.txt";

//open the file with write mode
$file = fopen($filename,"w");

//write the content of write
echo fwrite($file,"Hello World. Testing!");

//close the file
fclose($file);
?>

Write file line by line

<?php
//file name
$filename = "newFile.txt";

//open the file with write mode
$file = fopen($filename,"w");

$i=1;
while($i<=10)
{
fwrite($file,"this is line ".$i.PHP_EOL);
$i++;
}

echo $filename." written successfully!";

//close the file
fclose($file);
?>