function exportCsv(array $data, array $columns, string $filename = 'export.csv'): void {
// 1. 設定 Header(必須在任何輸出前)
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
header('Pragma: no-cache');
header('Expires: 0');
// 2. 開啟輸出流
$out = fopen('php://output', 'w');
// 3. 寫入 UTF-8 BOM(Excel 正確識別中文關鍵)
fwrite($out, "\xEF\xBB\xBF");
// 4. 寫入標題列
fputcsv($out, $columns);
// 5. 寫入資料
foreach ($data as $row) {
fputcsv($out, $row);
}
fclose($out);
exit;
}
// 使用
$data = [
['1', '張三', 'zhang@example.com'],
['2', '李四', 'li@example.com'],
];
exportCsv($data, ['ID', '姓名', 'Email'], 'users_' . date('Ymd') . '.csv');
Excel 開啟 CSV 時,若無 BOM 會誤判編碼導致中文亂碼。寫入 \xEF\xBB\xBF (UTF-8 BOM) 可確保 Excel 正確識別。
function exportLargeCsv(Generator $rows, array $columns, string $filename): void {
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
header('X-Accel-Buffering: no'); // 關閉 Nginx 緩衝,即時串流
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, $columns);
foreach ($rows as $row) {
fputcsv($out, $row);
// 可選:定期 flush 釋放緩衝
// if (++$i % 1000 === 0) flush();
}
fclose($out);
exit;
}
// 資料庫分塊查詢生成器
function getUsersChunked(PDO $pdo, int $chunkSize = 1000): Generator {
$stmt = $pdo->query('SELECT id, name, email FROM users');
while ($rows = $stmt->fetchAll(PDO::FETCH_NUM, $chunkSize)) {
foreach ($rows as $row) yield $row;
}
}
// 使用
exportLargeCsv(getUsersChunked($pdo), ['ID', '姓名', 'Email'], 'large_export.csv');
CSV 无法支援多工作表、樣式、公式、圖表。需求複雜時請用 phpoffice/phpspreadsheet。
// composer require phpoffice/phpspreadsheet
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('用戶列表');
// 標題樣式
$sheet->fromArray(['ID', '姓名', 'Email'], null, 'A1');
$sheet->getStyle('A1:C1')->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '4472C4']],
]);
// 資料(大量資料用 fromArray + chunk)
$sheet->fromArray($data, null, 'A2');
// 自動欄寬
foreach (range('A', 'C') as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
// 串流輸出(避免記憶體爆炸)
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="users_' . date('Ymd') . '.xlsx"');
$writer->save('php://output');
exit;
// 設定快取策略(預設記憶體,可改用 SQLite/Redis/檔案)
\PhpOffice\PhpSpreadsheet\Settings::setCacheStorage(
\PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::cache_to_phpTemp,
['memoryCacheSize' => '100MB'] // 超過寫入暫存檔
);
// 或使用批次寫入
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->setPreCalculateFormulas(false);
$writer->save('php://output');
| 現象 | 原因 | 解決 |
|---|---|---|
| Excel 開啟 CSV 中文亂碼 | 缺少 UTF-8 BOM | fwrite($out, "\xEF\xBB\xBF") |
| 檔案開頭有 HTML/空白 | 輸出前有 echo/空白/錯誤訊息 | ob_clean()、確保 header 前無輸出、關閉 display_errors |
| 大檔導出記憶體耗盡 | 一次性載入所有資料 | 分塊查詢 + Generator + php://output 串流 |
| 檔名中文下載亂碼 | Header 編碼問題 | rawurlencode($filename) 或 RFC 5987 格式 |
| 數字前導零消失(如 00123) | Excel 自動轉數值 | CSV: 在值前加 \t 或 =\"00123\";XLSX: 設定儲存格格式為文字 |
簡單場景用 fputcsv + php://output + UTF-8 BOM 最輕量高效;複雜報表用 PhpSpreadsheet 配合快取策略。核心原則:Header 先行、串流輸出、編碼正確、權限把關。