Skip to content
GreenSnippets

Read a large CSV file with a generator

Stream CSV rows as associative arrays using fgetcsv, without loading the whole file into memory.

PHP
<?php
/** @return Generator<int, array<string, string>> */
function readCsv(string $path): Generator
{
    $handle = fopen($path, 'rb');
    if ($handle === false) {
        throw new RuntimeException("Cannot open $path");
    }
    try {
        $header = fgetcsv($handle, 0, ',', '"', '');
        if ($header === false) {
            return;
        }
        while (($row = fgetcsv($handle, 0, ',', '"', '')) !== false) {
            if (count($row) === count($header)) {
                yield array_combine($header, $row);
            }
        }
    } finally {
        fclose($handle);
    }
}

Example / expected output

Output
foreach (readCsv('users.csv') as $row) {
    echo $row['email'], "\n";
}

How it works

A generator yields one row at a time, so memory use stays flat for huge files. The first row is used as the header. Rows with a different column count are skipped here; decide whether to throw instead for strict imports.