使用 iconv() 將 GB2312 編碼轉換為 UTF-8 時,部分漢字(如「??」)會觸發錯誤:
Notice: iconv() [function.iconv]: Detected an illegal character in input string
iconv('UTF-8', 'GB2312//IGNORE', $str);
或直接指定目標編碼為 GBK:
iconv('UTF-8', 'GBK', $str);
確認來源字串編碼是否正確,或在函數前加上 @ 抑制錯誤提示(不建議長期使用)。
mb_convert_encoding() 提供更穩健的編碼轉換支援:
<?php
header("content-Type: text/html; charset=Utf-8");
echo mb_convert_encoding("測試字串", "UTF-8", "GBK");
?>
同理可用於 GB2312 轉 Big5:
<?php
header("content-Type: text/html; charset=big5");
echo mb_convert_encoding("你是我的朋友", "big5", "GB2312");
?>
專案開發初期建議統一使用 UTF-8 編碼,減少轉碼需求;若必須轉碼,優先使用 mb_convert_encoding(),並做好異常處理。