November 6, 2012
How to read a file line by line in php
Question by adnan masood
How to read a file line by line in php, without completely loading it in memory.
Becuase my file is too large to open in memory so i always got memory exhaust error.
The file size is 1Gb.
Answer by Starx
Use buffering techniques to read the file.
$filename = "test.txt";
$source_file = fopen( $filename, "r" ) or die("Couldn't open $filename");
while (!feof($source_file)) {
$buffer = fread($source_file, 4096); // use a buffer of 4KB
$buffer = str_replace($old,$new,$buffer);
///
}