PHP: Stream a file line-by-line using a generator
Published:
This function will "stream" a file line-by-line, as a Generator
.
This can be very useful if you need to process a big file, line by line, without reading the whole thing into memory all at once.
function read($file)
{
$fp = fopen($file, 'rb');
while(($line = fgets($fp)) !== false)
yield rtrim($line, "\r\n");
fclose($fp);
}
Usage:
foreach(read('http://example.com') as $line)
{
var_dump($line);
}