Add to Favorites

PHP file processing in chunks

There comes a time when you too will need to process a large file that you don't want load all at once into memory. Luckily php makes this easy to do.

You open a file just as usual, $f = fopen('path_to_file','r');

You can then loop through it a little bit at a time, reading in chunks.

while ( ! feof($f) ) {

$chunk = fread($f,1024);

}

If you need to process a text file in lines instead of just chunks by byte size, you can use a different function but in the same way.

while ( ! feof($f) ) {

$line = fgets($f);

}

It's as easy as that ( don't forget to close your file handle, fclose($f); )

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up