通常网页有两种编码gbk和utf8,那么当我们获取网站内容后,有可能导致编码不统一而发生乱码。
今天在网络上找到了两种解决办法,并测试通过。
第一种:public static function strToGBK($strText){
$encode = mb_detect_encoding($strText, array("UTF-8","GB2312","GBK"));
if($encode == "GB2312"){
return @iconv("GB2312","UTF-8",$strText);
}else{
return $strText;
}
}
第二种:$text='要被转换的gbk字符串';
if(json_encode($text) == 'null'){
$text=iconv('gb2312','utf-8',$text);
}
json_encode()函数将得到的字符串进行编码。
因为该函数只能接受uft8,所以如果是gbk的话,就返回为null了,利用这个函数的特点进行判断是否是非UTF-8编码。
最后一点就是进行转换了。