mb_detect_encoding() 在某些環境下偵測不準。採用「嘗試轉碼後比對 MD5」策略:將檔案內容分別以候選編碼「轉回同編碼」,若 MD5 不變則判定為該編碼,再轉為目標編碼輸出。
<?php
function detect_encoding($file) {
$list = ['GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1'];
$str = file_get_contents($file);
foreach ($list as $enc) {
$tmp = mb_convert_encoding($str, $enc, $enc);
if (md5($tmp) === md5($str)) return $enc;
}
return null;
}
?>
<?php
function auto_read($file, $targetCharset = 'UTF-8') {
$list = ['GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1'];
$str = file_get_contents($file);
foreach ($list as $enc) {
$tmp = mb_convert_encoding($str, $enc, $enc);
if (md5($tmp) === md5($str)) {
return mb_convert_encoding($str, $targetCharset, $enc);
}
}
return '';
}
?>
<?php
$file = 'data.txt';
$enc = detect_encoding($file);
echo "偵測編碼:$enc\n";
$content = auto_read($file);
echo "內容(UTF-8):\n$content";
?>
fopen 串流處理。