<?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 中文拆成單字節,導致欄位錯位、截斷。
<?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,安全入庫/處理
}
<?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
<?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);
<?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` 自動處理,勿手動拼接 |
核心口訣:**Locale 先行,編碼轉換,BOM 檢測,UTF-8 落地**。只要這四步到位,CSV 亂碼問題 99% 可解。