Tag Archives: Yield

PHP: Stream a file line-by-line using a generator

This function will “stream” a file line-by-line, as a Generator.

Can be very useful if for example you need to process a big file, don’t want to read the whole thing into memory, but only process each line by itself.

function read($file)
    $fp = fopen($file, 'rb');

    while(($line = fgets($fp)) !== false)
        yield rtrim($line, "\r\n");


// Usage
foreach(read('http://example.com') as $line)