PHP

Stream Large CSV with Generator

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Iterate over a CSV file row-by-row without ever loading the whole file into memory. Uses a generator so consumers can foreach naturally and PHP cleans up the file handle.
PHP
Raw
<?php
function csvRows(string $path, string $sep = ',', string $enc = '"'): Generator {
    $fh = fopen($path, 'r');
    if ($fh === false) throw new RuntimeException("Cannot open $path");
    try {
        while (($row = fgetcsv($fh, 0, $sep, $enc, '\\')) !== false) {
            yield $row;
        }
    } finally {
        fclose($fh);
    }
}

foreach (csvRows('big-export.csv') as $i => $row) {
    if ($i === 0) continue;        // skip header
    // process $row — uses ~constant memory regardless of file size
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.