萬盛學電腦網

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

PHP 匯入 CSV 檔案亂碼終極解決方案:編碼偵測、setlocale、BOM 處理全攻略

亂碼根因分析

  1. 來源編碼不一:Excel 另存 CSV 預設用系統預設編碼(中文 Windows = CP936/GBK,Mac = UTF-8,Linux = UTF-8/GBK)
  2. PHP 讀取預期編碼不一:`fgetcsv()` 依賴 **locale (LC_CTYPE)** 判斷多位元組字元邊界,locale 錯誤導致截斷/亂碼
  3. 輸出端編碼不匹配**:資料庫/網頁/下載檔案編碼不一致

完整解決方案:四步走

步驟 1:設置正確 Locale(關鍵!)

<?php
// 必須在任何 fgetcsv/fputcsv 之前調用
// Linux/macOS: 安裝對應 locale (sudo apt-get install language-pack-zh-hans)
setlocale(LC_ALL, 'zh_CN.UTF-8', 'zh_CN', 'Chinese_China.936', 'chs');
// Windows 可能需用 'Chinese_China.936' 或 'chs'
// 驗證生效
echo "Current locale: " . setlocale(LC_CTYPE, '0') . "\n";

原理:`fgetcsv` 內部用 `setlocale` 決定的字符集來解析多位元組字元。錯誤 locale 會把 UTF-8 中文拆成單字節,導致欄位錯位、截斷。

步驟 2:偵測/強制指定來源編碼並轉為 UTF-8

<?php
function detectAndConvertToUtf8(string $str): string {
    // 嘗試偵測 (mbstring 必須啟用)
    $encoding = mb_detect_encoding($str, ['UTF-8', 'GBK', 'GB2312', 'BIG5', 'CP936'], true);
    if ($encoding && $encoding !== 'UTF-8') {
        return mb_convert_encoding($str, 'UTF-8', $encoding);
    }
    // 偵測失敗或已是 UTF-8
    // 進一步驗證是否為合法 UTF-8
    if (!mb_check_encoding($str, 'UTF-8')) {
        // 強制嘗試 GBK → UTF-8 (中文環境常見)
        $str = mb_convert_encoding($str, 'UTF-8', 'GBK');
    }
    return $str;
}

// 處理每一行/每一欄
while (($row = fgetcsv($handle, 0, ',')) !== false) {
    $row = array_map('detectAndConvertToUtf8', $row);
    // 現在 $row 全是 UTF-8,安全入庫/處理
}

步驟 3:處理 BOM (Byte Order Mark)

<?php
$handle = fopen($filePath, 'r');
// 讀取前 3 位元組檢查 UTF-8 BOM (EF BB BF)
$bom = fread($handle, 3);
if ($bom !== "\xEF\xBB\xBF") {
    rewind($handle); // 無 BOM,重置指標
} // 有 BOM 則指標已在正確位置,直接 fgetcsv

步驟 4:統一輸出/儲存為 UTF-8 (無 BOM)

<?php
// 入庫前確保連線編碼
$pdo->exec("SET NAMES utf8mb4");

// 導出 CSV 時
$fp = fopen('php://output', 'w');
// 可選:加 BOM 讓 Excel 直接開啟不亂碼
fwrite($fp, "\xEF\xBB\xBF");
fputcsv($fp, ['欄位1', '欄位2', '欄位3']); // 表頭
foreach ($data as $row) {
    fputcsv($fp, $row);
}
fclose($fp);

完整可用類:CsvImporter

<?php
class CsvImporter {
    private string $filePath;
    private array $options;

    public function __construct(string $filePath, array $options = []) {
        $this->filePath = $filePath;
        $this->options = array_merge([
            'delimiter' => ',',
            'enclosure' => '"',
            'escape'    => '\\',
            'encoding'  => 'auto', // auto/UTF-8/GBK/BIG5...
            'has_header' => true,
            'locale'    => 'zh_CN.UTF-8',
        ], $options);
    }

    public function import(callable $rowCallback): int {
        setlocale(LC_ALL, $this->options['locale']);
        
        $handle = fopen($this->filePath, 'r');
        if (!$handle) throw new RuntimeException("Cannot open file: {$this->filePath}");

        // BOM 處理
        $bom = fread($handle, 3);
        if ($bom !== "\xEF\xBB\xBF") rewind($handle);

        $header = null;
        $count = 0;

        while (($row = fgetcsv($handle, 0, $this->options['delimiter'], $this->options['enclosure'], $this->options['escape'])) !== false) {
            if ($this->options['has_header'] && $header === null) {
                $header = $row;
                continue;
            }
            
            // 編碼轉換
            if ($this->options['encoding'] !== 'UTF-8') {
                $from = $this->options['encoding'] === 'auto' ? null : $this->options['encoding'];
                $row = array_map(fn($v) => $this->convert($v, $from), $row);
            }

            $data = $header ? array_combine($header, $row) : $row;
            $rowCallback($data, $count);
            $count++;
        }
        fclose($handle);
        return $count;
    }

    private function convert(string $str, ?string $from): string {
        if ($from) return mb_convert_encoding($str, 'UTF-8', $from);
        $detected = mb_detect_encoding($str, ['UTF-8','GBK','BIG5','CP936'], true);
        return $detected && $detected !== 'UTF-8' ? mb_convert_encoding($str, 'UTF-8', $detected) : $str;
    }
}

// 使用
$importer = new CsvImporter('data.csv', ['encoding' => 'auto', 'locale' => 'zh_CN.UTF-8']);
$importer->import(function(array $row, int $index) {
    // $row 為關聯陣列 (有表頭) 或索引陣列
    User::create($row);
});

常見坑點速查表

現象原因解決
中文變 `???` 或亂碼來源 GBK,PHP 以 UTF-8 讀取`setlocale(LC_ALL, 'zh_CN.UTF-8')` + `mb_convert_encoding($str, 'UTF-8', 'GBK')`
欄位內容被截斷/合併Locale 錯誤導致多位元組字元邊界判斷錯正確設定 `setlocale`,確保系統安裝對應 locale
第一行表頭亂碼UTF-8 BOM 未移除讀取前 3 字節檢測 BOM,有則跳過
Excel 開啟導出 CSV 亂碼Excel 預期帶 BOM 的 UTF-8導出前 `fwrite($fp, "\xEF\xBB\xBF")`
換行符混亂 (CRLF/LF/CR)跨平台產生`fgetcsv` 自動處理;導出統一 `PHP_EOL` 或 `\r\n`
欄位包含逗號/引號/換行CSV 標準要求雙引號包裹、雙引號轉義用 `fputcsv` 自動處理,勿手動拼接

大檔案處理技巧

  • **分塊處理**:`fgetcsv` 本身逐行讀取,配合 Generator 逐行 yield 給處理邏輯
  • **資料庫批量插入**:累積 500-1000 條 `INSERT ... VALUES (...),(...),...` 執行一次
  • **記憶體監控**:`memory_get_peak_usage()` 觀察,必要時 `unset($row)`、`gc_collect_cycles()`
  • **並行導入**:將大檔案切分 (split -l 10000),多進程並行導入不同分片

核心口訣:**Locale 先行,編碼轉換,BOM 檢測,UTF-8 落地**。只要這四步到位,CSV 亂碼問題 99% 可解。

copyright © 萬盛學電腦網 all rights reserved