mb_detect_encoding() 是用作檢查字串編碼的 PHP 函式, 使用上很方便, 例如:
|
1 2 3 4 |
<?php $str = "中文測試"; echo mb_detect_encoding($str); ?> |
以上程式碼會印出 $str 的編碼, 例如 UTF-8。
iconv() 則是用作轉換字串編碼的函式, 例如我想將 BIG5 編碼轉到 UTF-8, 是這樣寫:
|
1 2 3 4 |
<?php $new_str = iconv("BIG5", "UTF-8", "BIG5 文字"); echo $new_str; ?> |
將上面的 mb_detect_encoding() 及 iconv() 配合使用, 可以先得出字串編碼, 然後做轉換:
|
1 2 3 4 |
<?php $str = "中文測試"; $new_str = iconv(mb_detect_encoding($str), "UTF-8", $str); ?> |