Export a query to CSV

Stream rows straight to the browser as a CSV download.

PHP · Export a query to CSVIntermediate
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="users.csv"');

$out = fopen('php://output', 'w');
fputcsv($out, ['ID', 'Name', 'Email']);
foreach ($pdo->query('SELECT id, name, email FROM users') as $row) {
    fputcsv($out, $row);
}
fclose($out);
csvexportdownload