Read a large CSV file with a generator
Stream CSV rows as associative arrays using fgetcsv, without loading the whole file into memory.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?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
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.
Related snippets
- Python Tested
Read a CSV file as dictionaries
Stream CSV rows as dicts keyed by header with csv.DictReader, handling UTF-8 BOMs and quoted commas.
- Bash
Delete files older than N days
Safely remove old log or temp files with find, previewing first and handling unusual filenames.
- Python Tested
Write a file atomically
Write to a temporary file and rename it into place so readers never see a half-written file.
- Bash
Timestamped tar.gz backup that keeps the newest N
Archive a directory with a sortable timestamp and delete older backups beyond a retention count.

