CSV 為最通用的表格交換格式。PHP 產生 CSV 下載需正確設定 Header、處理 UTF-8 BOM(Excel 相容)、大檔分塊輸出避免記憶體溢位。本文提供三種場景完整代碼:現有檔案下載、陣列資料即時生成、百萬列分塊串流。
<?php
$filePath = '/data/exports/prefs.csv';
$fileName = 'prefs_' . date('Ymd_His') . '.csv';
if (!is_file($filePath)) {
http_response_code(404);
exit('檔案不存在');
}
// 關鍵:清除輸出緩衝,防止 BOM/空白/錯誤訊息污染
while (ob_get_level()) ob_end_clean();
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filePath));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($filePath);
exit;
<?php
$data = [
['ID', '姓名', 'Email', '註冊時間'],
[1, '張三', 'zhang@example.com', '2024-01-15 10:30:00'],
[2, '李四', 'li@example.com', '2024-01-16 14:22:00'],
];
$fileName = 'members_' . date('Ymd_His') . '.csv';
while (ob_get_level()) ob_end_clean();
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
// 輸出 UTF-8 BOM (EF BB BF),Excel 開啟不亂碼
echo "\xEF\xBB\xBF";
$out = fopen('php://output', 'w');
foreach ($data as $row) {
fputcsv($out, $row);
}
fclose($out);
exit;
<?php
$fileName = 'huge_export_' . date('Ymd_His') . '.csv';
while (ob_get_level()) ob_end_clean();
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
$out = fopen('php://output', 'w');
echo "\xEF\xBB\xBF"; // BOM
// 模擬資料來源:資料庫游標 / Generator
function dataGenerator(): Generator {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=demo', 'user', 'pass');
$stmt = $pdo->query('SELECT id, name, email, created_at FROM members');
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
yield $row;
}
}
$first = true;
foreach (dataGenerator() as $row) {
if ($first) {
fputcsv($out, ['ID', '姓名', 'Email', '註冊時間']); // 表頭
$first = false;
}
fputcsv($out, $row);
// 可選:每 1000 列 flush 避免 nginx/proxy 緩衝超時
if (++$cnt % 1000 === 0) flush();
}
fclose($out);
exit;
| 目標環境 | 建議編碼 | BOM | 分隔符 |
|---|---|---|---|
| Excel 2016+ / LibreOffice / Google Sheets | UTF-8 | 建議加 | , |
| Excel 2010-2013 (舊版) | UTF-8 | 必須加 | , |
| 中文舊系統 (內碼 GBK) | GBK/CP936 | 不加 | , |
| 歐洲地區 | UTF-8 | 建議加 | ; (分號) |
若需 GBK 輸出:iconv('UTF-8', 'GBK//IGNORE', $cell) 逐欄位轉碼,或整行 iconv('UTF-8', 'GBK//IGNORE', implode(',', $row))。
前無任何字元,結尾省略 ?>。proxy_read_timeout、PHP max_execution_time 需調大;建議啟用 X-Accel-Redirect (Nginx) / X-Sendfile (Apache) 讓 Web Server 直接傳檔。