PHP Generators: Processing a File Bigger Than Memory
PHP Generators: Processing a File Bigger Than Memory

The import worked on the sample file. It died on the real one.
PHP Fatal error: Allowed memory size of 268435456 bytes exhausted
(tried to allocate 20480 bytes) in /app/Imports/LedgerImport.php on line 34
The code that produced it is the code almost everyone writes first, and it is not obviously wrong:
function readLedger(string $path): array
{
$rows = [];
$fh = fopen($path, 'r');
$headers = fgetcsv($fh);
while (($row = fgetcsv($fh)) !== false) {
$rows[] = array_combine($headers, $row);
}
fclose($fh);
return $rows;
}
foreach (readLedger($path) as $row) {
Ledger::create($row);
}
The function has to finish before the loop starts. Finishing means every row of a 400MB file is an associative array in memory at once — and a PHP array of arrays is several times the size of the text it came from. The loop then processes them one at a time, which is all it ever needed.
The change
function readLedger(string $path): Generator
{
$fh = fopen($path, 'r');
$headers = fgetcsv($fh);
while (($row = fgetcsv($fh)) !== false) {
yield array_combine($headers, $row);
}
fclose($fh);
}
Two lines different: $rows[] = became yield, and the array bookkeeping disappeared. The call site is unchanged — foreach does not care which it is given.
Memory goes from roughly the size of the whole file to the size of one row. Not proportionally less; constant, regardless of whether the file has ten thousand rows or ten million.

What yield actually does
The mental model that makes generators click: a function containing yield does not run when you call it. Calling it returns a Generator object and executes nothing.
function counter(): Generator
{
echo "startingn";
yield 1;
echo "betweenn";
yield 2;
echo "donen";
}
$gen = counter(); // prints nothing at all
echo "createdn";
foreach ($gen as $value) {
echo "got $valuen";
}
// created
// starting
// got 1
// between
// got 2
// done
Each time the loop asks for a value, the function runs until the next yield, hands the value over, and freezes exactly there — local variables, loop position, open file handle and all. The next iteration resumes from that line.
Which is why the file handle in readLedger stays open across the whole loop, and why fclose at the bottom does eventually run: the function really is suspended mid-execution, not restarted.
The one that catches everyone
A generator can be iterated exactly once.
$rows = readLedger($path);
$count = iterator_count($rows); // consumes the generator
foreach ($rows as $row) { ... } // runs zero times, silently
No error. The loop simply does not execute, because the generator is finished. Trying again throws Exception: Cannot traverse an already closed generator only if you call rewind() explicitly; the plain foreach just does nothing, which is considerably harder to debug.
So count() does not work on a generator either, and neither does array access, array_map, or anything else expecting a countable, indexable structure. If you need the count and the rows, either count during the single pass or accept reading the file twice.
A generator is a stream, not a collection. Everything surprising about it follows from that.
Composing them
The real gain is that generators chain without any stage materialising its output.
function onlyPaid(iterable $rows): Generator
{
foreach ($rows as $row) {
if ($row['status'] === 'paid') {
yield $row;
}
}
}
function withTax(iterable $rows): Generator
{
foreach ($rows as $row) {
$row['tax'] = $row['amount'] * 0.18;
yield $row;
}
}
foreach (withTax(onlyPaid(readLedger($path))) as $row) {
Ledger::create($row);
}
Three stages, one row in memory. Written with arrays, each stage would build a complete intermediate copy, and the filter stage would hold most of the file before the tax stage saw its first row.
Taking the iterable type hint rather than Generator is deliberate: these functions then accept a plain array too, which makes them trivial to unit test without building a generator in the test.
yield from
function allLedgers(array $paths): Generator
{
foreach ($paths as $path) {
yield from readLedger($path);
}
}
Delegates to another generator and passes its values straight through. Twelve monthly files read as one continuous stream, still one row at a time.
One sharp edge: yield from preserves the inner generator’s keys, so two files both yielding keys 0..n produce duplicate keys in the combined stream. Harmless in a foreach over values; destructive the moment you call iterator_to_array() without the second argument:
iterator_to_array($gen); // later duplicate keys overwrite earlier rows
iterator_to_array($gen, false); // reindexed — what you almost always meant

Where this shows up in Laravel
The framework wraps generators in a friendlier interface, and it is the same mechanism underneath.
// loads every matching row into memory
Invoice::where('status', 'pending')->get()->each(fn ($i) => $i->remind());
// one model at a time, backed by a generator
Invoice::where('status', 'pending')->cursor()->each(fn ($i) => $i->remind());
// a thousand rows per query, one chunk in memory
Invoice::where('status', 'pending')->lazy()->each(fn ($i) => $i->remind());
The difference between cursor() and lazy() matters more than it looks. cursor() runs one query and streams the result set, which means the database holds the whole result and the connection stays busy for the duration. lazy() runs repeated chunked queries, so each is short.
For a long-running job, lazy() is usually the safer choice — a cursor held open for twenty minutes is a connection held open for twenty minutes, and on shared hosting that is the kind of thing that gets a process killed. LazyCollection also gives you map, filter and chunk over the stream, so the composition above reads more naturally.
One warning about lazy(): it paginates by primary key, so modifying the column you are ordering by, mid-iteration, can skip or repeat rows. Use lazyById() and do not update the id.
Where generators do not help
Three cases, because refactoring to generators where they cannot help is a real cost.
When you need the whole thing anyway. Sorting requires every element. So does any aggregate over the full set that is not incremental. A generator that gets immediately passed to iterator_to_array() has bought nothing but indirection.
When the data is small. A generator over 200 rows saves a few kilobytes and costs readability. Arrays are simpler and simpler is correct here.
When you need random access. $rows[47] is not available on a stream, and neither is going back. If the algorithm needs to look at row 12 while processing row 900, a generator is the wrong shape.
There is also a speed point worth being honest about: generators are not faster. Per-item, they are marginally slower than an array loop. The win is memory, and memory is usually what was actually failing.
Errors mid-stream
A 400,000-row import will contain a bad row, and the question is what happens to the other 399,999.
function readLedger(string $path): Generator
{
$fh = fopen($path, 'r');
$headers = fgetcsv($fh);
$line = 1;
try {
while (($row = fgetcsv($fh)) !== false) {
$line++;
if (count($row) !== count($headers)) {
yield ['__error' => "line {$line}: expected " . count($headers) . " columns, got " . count($row)];
continue;
}
yield array_combine($headers, $row);
}
} finally {
fclose($fh); // runs even if the consumer breaks out early
}
}
The finally is the part worth copying. If the consuming loop hits break, or throws, the generator is destroyed without reaching the line after the while — so a bare fclose() at the bottom never runs. With finally, PHP runs it during destruction.
Yielding the error rather than throwing it lets the caller decide: skip and log, or stop. Throwing from inside the generator ends the stream for everyone, which is right for a corrupt file and wrong for one bad row.

Sending values back in
yield is an expression, not a statement, which means a generator can receive as well as produce. This is the least-used half of the feature and it has one genuinely good use.
function batchWriter(int $size): Generator
{
$batch = [];
while (true) {
$row = yield; // receives whatever send() passes
if ($row === null) break; // caller signalling the end
$batch[] = $row;
if (count($batch) >= $size) {
Ledger::insert($batch);
$batch = [];
}
}
if ($batch) Ledger::insert($batch);
}
$writer = batchWriter(500);
$writer->current(); // prime it — runs up to the first yield
foreach (readLedger($path) as $row) {
$writer->send($row);
}
$writer->send(null);
That turns 400,000 individual inserts into 800 bulk inserts, with the batching logic owned by the writer rather than smeared across the import loop as a counter and an array the caller has to remember to flush.
Two things to watch. The generator must be primed — a send() before the generator has reached its first yield throws. And the final flush only happens if the caller signals the end, so a loop that returns early leaves the last partial batch unwritten. In practice, a LazyCollection::chunk(500) is easier to get right and does the same job; the send() version is worth knowing mainly so the syntax is not baffling when you meet it.
Return values, and what the consumer sees
A generator can also return a value at the end, separate from everything it yielded.
function readLedger(string $path): Generator
{
$ok = 0; $bad = 0;
// ...
// $ok++ or $bad++ as each row goes by
return ['imported' => $ok, 'skipped' => $bad];
}
$rows = readLedger($path);
foreach ($rows as $row) { ... }
$stats = $rows->getReturn(); // only valid after the loop finishes
This solves the counting problem from earlier without a second pass: the generator tallies as it goes and hands over the totals when the stream ends. getReturn() before the generator has completed throws, so it belongs strictly after the loop — and it cannot be reached at all if the consumer broke out early, which is worth a thought before relying on it for a summary email.
A quick way to see the difference
The argument is more convincing measured than described, and it takes four lines.
$before = memory_get_peak_usage(true);
$count = 0;
foreach (readLedger($path) as $row) { $count++; }
printf("%d rows, peak %.1f MB
", $count, (memory_get_peak_usage(true) - $before) / 1048576);
Run it against both versions of readLedger. The array version’s peak scales with the file; the generator version’s peak barely moves between a 5MB file and a 500MB one. memory_get_peak_usage(true) with the true argument reports real memory claimed from the system, which is the number that matters when the limit is what killed the process — the default reports PHP’s internal accounting and reads lower.
It is worth doing once on real data rather than trusting the reasoning, because the other thing the measurement catches is a stage in the middle that silently materialises everything — an array_filter or a sort slipped into a chain of generators undoes the whole benefit, and the memory graph is the only place that shows up.
Streaming a download out, not just a file in
The mirror image of the import problem is the export, and it fails the same way: building a 200,000-row CSV in memory before sending it.
return response()->streamDownload(function () {
$out = fopen('php://output', 'w');
fputcsv($out, ['number', 'customer', 'amount', 'status']);
foreach (Invoice::lazyById(1000) as $invoice) {
fputcsv($out, [
$invoice->number,
$invoice->customer_name,
$invoice->amount,
$invoice->status,
]);
}
fclose($out);
}, 'invoices.csv', ['Content-Type' => 'text/csv']);
Rows go to the browser as they are read, so peak memory is one chunk regardless of the export size, and the user’s download starts immediately instead of after a two-minute wait.
Two practical notes. Output buffering will undo this — if something upstream has a buffer open, PHP collects the whole response anyway, so a flush() every few hundred rows is cheap insurance. And because headers are sent before the loop runs, an exception halfway through cannot become a 500 page: the user gets a truncated CSV with a 200 status. For anything important, validate before you start streaming, and log failures rather than relying on the response to report them.
Where the memory actually went
One last thing that explains the numbers, because “arrays are big” is not a satisfying answer.
A PHP array is a hash table, and each element carries a bucket with a hash, a key pointer, a value zval and collision links. For an array of strings, that overhead is usually larger than the strings themselves. An associative array per CSV row also stores the header names — so a 400,000-row file with twelve columns keeps 4.8 million string keys alive, almost all of them the same twelve words repeated.
PHP 7 onward interns identical literal strings, which helps, but keys built at runtime by array_combine are not literals. If a batch job is close to the limit and a generator is not an option, switching from array_combine($headers, $row) to positional access on the raw $row, or to a small object with declared properties, removes that duplication. An object with typed properties is genuinely smaller than an associative array with the same fields, which surprises people who expect objects to be the heavier choice.
None of that is a substitute for streaming. It is worth knowing mainly so the peak number makes sense when you measure it, and so the fix is not mistaken for a rounding error.
The shape of the fix
The original function’s problem was not the file size. It was that it promised an array, and a promise of an array is a promise to hold all of it.
Changing the return type to Generator changes the promise to “I will give you rows as you ask for them”, and every caller that was already doing foreach — which is most of them — needs no change at all. That is why this refactor is usually a one-line diff in the producer and nothing anywhere else.

