Stream a large CSV download
Write rows straight to the browser one by one. Memory stays small for millions of rows. Cells starting with = + - @ are neutralised.
PHP · Stream a large CSV downloadAdvanced
function csvSafe(mixed $v): mixed
{
if (is_string($v) && $v !== '' && strpbrk($v[0], "=+-@\t\r") !== false) {
return "'" . $v; // stops spreadsheet formula injection
}
return $v;
}
function streamCsv(string $filename, array $header, iterable $rows): void
{
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF"); // BOM so Excel reads UTF-8
fputcsv($out, $header);
foreach ($rows as $row) {
fputcsv($out, array_map('csvSafe', $row));
}
fclose($out);
}
function rows(PDO $pdo): Generator
{
$st = $pdo->query('SELECT id, name, email FROM users');
while ($r = $st->fetch(PDO::FETCH_NUM)) {
yield $r;
}
}
// streamCsv('users.csv', ['id', 'name', 'email'], rows($pdo));csvexportgeneratormemory