PHP stream a text file line by line
PHP
<?php
function read_lines(string $path): Generator
{
$handle = fopen($path, 'rb');
if ($handle === false) {
throw new RuntimeException('Cannot open file: ' . $path);
}
try {
while (($line = fgets($handle)) !== false) {
yield rtrim($line, chr(13) . chr(10));
}
} finally {
fclose($handle);
}
}