Heim  >  Artikel  >  php教程  >  php5.2 Json不能正确处理中文的解决办法

php5.2 Json不能正确处理中文的解决办法

WBOY
WBOYOriginal
2016-06-06 19:56:251139Durchsuche

php5.2新增的json功能是非常受欢迎的,但是经过测试发现, json_encode对中文的处理是有问题的, 1.不能处理GB编码,所有的GB编码都会替换成空字符。 2.utf8编码的中文被编码成unicode编码,相当于javascript的escape函数处理的结果。 为了能正确使用json,

    php5.2新增的json功能是非常受欢迎的,但是经过测试发现,

    json_encode对中文的处理是有问题的,

    1.不能处理GB编码,所有的GB编码都会替换成空字符。

    2.utf8编码的中文被编码成unicode编码,相当于javascript的escape函数处理的结果。

    为了能正确使用json,首先我们就应该在编码上采用utf8编码,然后再对json_encode的返回结果稍加处理就可以得到正确的结果了。

    我写了一个简单的类,将这两个函数包装了一下,

class Json{  

 public static function encode($str){  

 $code = json_encode($str);  

 return preg_replace("#\\\u([0-9a-f]+)#ie""iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))"$code);  

}   
 public static function decode($str){  

 return json_decode($str);  

 }  


    使用的时候

Json::encode($code);  

Json::decode($code); 

    这样可以正确处理utf8编码的中文了。

    PS:对于GB编码的中文,我们可以在编码时先转成UTF8编码,再进行编码,解码的时候再进行一个utf8 -> gb的转换就可以了。

    另外一般json_encode的结果我们是返回到客户端来使用,我们其实还可以用javascript的unescape函数来对unicode编码的中文进行解码,从而还原成正确的中文。

    或者用:$title = mb_convert_encoding($title, 'HTML-ENTITIES', $this->_outCharset);//任意编码下都正常显示


php5.2 Json不能正确处理中文的解决办法

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn