I want to read a file line by line, but without completely loading it in memory.
My file is too large to open in memory, and if try to do so I always get out of memory errors.
The file size is 1 GB.
asked Nov 6, 2012 at 7:49
adnan masoodadnan masood
5,6752 gold badges12 silver badges6 bronze badges
2
You can use the fgets[]
function to read the file line by line:
$handle = fopen["inputfile.txt", "r"];
if [$handle] {
while [[$line = fgets[$handle]] !== false] {
// process the line read.
}
fclose[$handle];
}
answered Nov 6, 2012 at 7:51
codaddictcodaddict
434k80 gold badges487 silver badges524 bronze badges
7
if [$file = fopen["file.txt", "r"]] {
while[!feof[$file]] {
$line = fgets[$file];
# do same stuff with the $line
}
fclose[$file];
}
answered Nov 6, 2012 at 7:55
3
You can use an object oriented interface class for a file - SplFileObject //php.net/manual/en/splfileobject.fgets.php [PHP 5 >= 5.1.0]