Stream a downloadable CSV report in PHP
PHP
<?php
declare(strict_types=1);
/** Stream rows as a CSV download without holding the file in memory. */
function send_csv(array $rows, string $filename = 'export.csv'): void
{
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
$stream = fopen('php://output', 'wb');
if ($stream === false) {
throw new RuntimeException('cannot open output stream');
}
// UTF-8 BOM so spreadsheet apps detect the encoding.
fwrite($stream, "\xEF\xBB\xBF");
foreach ($rows as $row) {
fputcsv($stream, array_values($row));
}
fclose($stream);
}
$authors = [
['name' => 'Ada Lovelace', 'snippets' => 12],
['name' => 'Grace Hopper', 'snippets' => 9],
];
send_csv($authors, 'authors.csv');