How to read a file line by line in PHP, without completely loading it in memory?
My file is too large to open in memory so I always got memory exhaust errors.
The file size is 1Gb.
Join Stack Overflow to learn, share knowledge, and build your career.
|
How to read a file line by line in PHP, without completely loading it in memory? My file is too large to open in memory so I always got memory exhaust errors. The file size is 1Gb. |
||||
|
You can use the
|
|||||||||||||||||||||
|
|
|||||||||||||||||
|
|
You can use an object oriented interface class for a file - SplFileObject http://php.net/manual/en/splfileobject.fgets.php (PHP 5 >= 5.1.0)
|
|||||||||||||||||||||
|
|
Use buffering techniques to read the file.
|
|||||||||
|
|
There is a
|
|||||||||||||||||
|
|
||||
|
|
|
If you're opening a big file, you probably want to use Generators alongside fgets() to avoid loading the whole file into memory:
Use it like this:
This way you can process individual file lines inside the foreach(). Note: Generators require >= PHP 5.5 |
|||
|
|
|
Be careful with the 'while(!feof ... fgets()' stuff, fgets can get an error (returnfing false) and loop forever without reaching the end of file. codaddict was closest to being correct but when your 'while fgets' loop ends, check feof; if not true, then you had an error. |
|||
|
|
|
One of the popular solutions to this question will have issues with the new line character. It can be fixed pretty easy with a simple
|
|||
|
|
|
This how I manage with very big file (tested with up to 100G). And it's faster than fgets()
|
|||
|
|
|
Function to Read with array return
|
|||||
|
fgets()without$lengthparameter. – Carlos Nov 6 '12 at 7:51