Example
<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="users.csv"');
$output = fopen('php://output', 'w');
fputcsv($output, ['Name', 'Email']);
$stmt = $pdo->query('SELECT name, email FROM users');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$safeCells = [];
foreach ([$row['name'], $row['email']] as $value) {
$value = (string) $value;
// Prefix potentially interpreted spreadsheet formulas.
if (preg_match('/^[=+\-@\t\r]/', $value)) {
$value = "'" . $value;
}
$safeCells[] = $value;
}
fputcsv($output, $safeCells);
}
fclose($output);
exit;
Explanation
Writing directly to php://output avoids building the entire export in memory. fputcsv() handles CSV field quoting.
For large exports, stream rows in batches. Consider spreadsheet formula injection when exporting untrusted values.