Home > Backend Development > PHP Tutorial > php json_decode parses Chinese

php json_decode parses Chinese

WBOY
Release: 2016-08-08 09:31:44
Original
2033 people have browsed it
$arr = array ('a'=>'北京'); echo json_encode($arr);

以上代码执行后输出:

{“a”:”\u5317\u4eac”}

PHP 底层已经做了 unicode 处理,如果嫌它不够直观,可以利用 urlencode 和 urldecode 方法绕过这个转码为 unicode 的过程:

$arr = array ('a'=>urlencode('北京')); echo urldecode(json_encode($arr));

以上代码执行后输出:{“a”:”北京”}

但是对于抓取来的 json 我们没办法修改别人的服务器,有这么一个方法可处理;

$code = json_encode($str); $code = preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $code); print_r( mb_convert_encoding(stripslashes($code), "GBK", "UTF-8") );

另:在 php cli 模式下不能输出 utf-8 编码的字符,原因是 cmd 下只能显示 936 编码
处理办法是,把utf-8 编码的内容用 mb_convert_encoding 函数转化一下:如下

mb_convert_encoding("utf-8 的内容", "GBK", "UTF-8");

以上就介绍了php json_decode 解析中文,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template