萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 產生與下載 CSV 檔案完整指南:檔案流、字串直輸、編碼轉換、大檔分塊

CSV 為最通用的表格交換格式。PHP 產生 CSV 下載需正確設定 Header、處理 UTF-8 BOM(Excel 相容)、大檔分塊輸出避免記憶體溢位。本文提供三種場景完整代碼:現有檔案下載、陣列資料即時生成、百萬列分塊串流。

場景一:現有 CSV 檔案直接下載

<?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;

場景二:陣列資料即時生成 CSV(含 UTF-8 BOM 讓 Excel 正確識別中文)

<?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 SheetsUTF-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))。

常見坑點

  • 輸出前有空白/換行:檔案頂部 前無任何字元,結尾省略 ?>。
  • fputcsv 預設雙引號包裹:欄位含逗號、雙引號、換行會自動加引號並轉義,符合 RFC 4180。
  • 大檔案下載中斷:Nginx proxy_read_timeout、PHP max_execution_time 需調大;建議啟用 X-Accel-Redirect (Nginx) / X-Sendfile (Apache) 讓 Web Server 直接傳檔。
copyright © 萬盛學電腦網 all rights reserved