使用 fgetcsv() 讀取 CSV,明明第二欄是「訊息」,strlen() 比對卻發現長度不同,== 判斷失敗。根因通常是 CSV 檔案編碼為 EUC-CN (GBK),而 PHP 腳本預設為 UTF-8。
$encoding = mb_detect_encoding($buf[1], 'UTF-8, EUC-CN, ASCII'); var_dump($encoding); // 輸出 EUC-CN
$clean = mb_convert_encoding($buf[1], 'UTF-8', 'EUC-CN'); if ($clean === '訊息') echo '比對成功';
function readCsvUtf8(string $path, int $maxLen = 0, string $delimiter = ','): \Generator
{
$handle = fopen($path, 'r');
if (!$handle) throw new RuntimeException('無法開啟檔案');
while (($row = fgetcsv($handle, $maxLen, $delimiter)) !== false) {
yield array_map(
fn($cell) => mb_convert_encoding($cell, 'UTF-8', 'EUC-CN'),
$row
);
}
fclose($handle);
}
// 使用
foreach (readCsvUtf8('test.csv') as $i => $row) {
if ($i === 0) continue; // 跳過標題列
if ($row[1] === '訊息') echo '第 ' . ($i+1) . ' 列符合';
}
fseek($handle, 3) 跳過。SplFileObject 以物件導向方式處理。mb_detect_encoding($str, 'UTF-8, GBK, BIG5, ASCII', true) 強制偵測。