PHP中的mb_detect_encoding和mb_convert_encoding方法获取编码和转码问题

查看:179
本文介绍了PHP中的mb_detect_encoding和mb_convert_encoding方法获取编码和转码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

  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;

解决方案

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

这篇关于PHP中的mb_detect_encoding和mb_convert_encoding方法获取编码和转码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆