萬盛學電腦網

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

PHP Header 導出 Excel/CSV 完整指南:編碼、大資料、記憶體優化

基本導出流程

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');

關鍵細節解析

編碼處理:UTF-8 BOM 是關鍵

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');

導出真正的 Excel (.xlsx):使用 PhpSpreadsheet

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;

大量資料 .xlsx 記憶體優化:Cell Caching

// 設定快取策略(預設記憶體,可改用 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 BOMfwrite($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: 設定儲存格格式為文字

安全性提醒

  • 導出權限控管:確認使用者授權後才允許導出敏感資料。
  • 避免導出密碼、Token、身分證等敏感欄位。
  • 大量導出考慮非同步產生檔案、簽名 URL 限時下載,避免阻塞 Web 進程。

總結

簡單場景用 fputcsv + php://output + UTF-8 BOM 最輕量高效;複雜報表用 PhpSpreadsheet 配合快取策略。核心原則:Header 先行、串流輸出、編碼正確、權限把關。

copyright © 萬盛學電腦網 all rights reserved