PHP中的mb_detect_encoding和mb_convert_encoding方法取得編碼和轉碼問題
高洛峰
高洛峰 2017-05-16 13:14:00
0
1
473
  1. 用mb_detect_encoding得到的回傳值是cp936這個與GBK對應?

  2. 透過mb_convert_encoding轉碼後,雖然文字顯示正常,但在用mb_detect_encoding偵測文字編碼格式,仍然是cp936,並沒有改變,這是為什麼?

程式碼如下:

$file_contents = fread($file,$fileSize);

$typeofData = mb_detect_encoding($file_contents,array("GBK","GB2312","UTF-8","ASCII","BIG5"));

if ($typeofData != "UTF-8"){
//    $file_contents = iconv("GBK","UTF-8",$file_contents);
    $file_contents = mb_convert_encoding($file_contents,"UTF-8","GBK");
}

echo  mb_detect_encoding($file_contents,array("GBK","GB2312","UTF-8","ASCII","BIG5"))."<br/>";
echo $file_contents;
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回覆(1)
伊谢尔伦

GBK的Code Page是CP936.
我在Ubuntu上用PHP5和PHP7都試過了,轉成UTF-8編碼後能夠檢測到UTF-8:

<?php
$str = file_get_contents('/path/to/gbk.txt'); //GBK编码的文本文件
$order = array('GB2312', 'GBK', 'GB18030', 'UTF-8', 'ASCII', 'BIG5');
$encode = mb_detect_encoding($str, $order, true); //可见CP936(即GBK)
$str = mb_convert_encoding($str, 'UTF-8', $encode); //转成UTF-8
echo mb_detect_encoding($str, $order, true); //输出UTF-8
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板