使用 php 自带的 json_encode
函数对数据进行编码时,中文都会变成 unicode,导致不可读,并且增加传输数据的大小,比如,对字符串“我爱水煮鱼”进行 json_encode
后,输出的是”\u6211\u7231\u6c34\u716e\u9c7c”,那么如何使得中文不被 json_encode 不编码成 unicode 呢,有两种方法:
1. 先将中文字段 urlencode
,json_encode
后,再用 urldecode
,也可以显示中文。
echo urldecode(json_encode(urlencode("我爱水煮鱼")));
2. 如果使用的 PHP 版本是 5.4 以上的版本,json_encode
函数已经新增了一个选项: JSON_UNESCAPED_UNICODE
。加上这个选项后,就不会自动把中文编码了。
echo json_encode("我爱水煮鱼", JSON_UNESCAPED_UNICODE);
<?php //json_decode() 解码,即将json格式字符串解码成array或者对象 $json_str = '{"name":"张飞","age":23}'; $json_obj = json_decode($json_str); print_r($json_obj); //输出对象 stdClass Object ( [name] => 张飞 [age] => 23 ) echo '<br>' $json_obj = json_decode($json_str,true); print_r($json_obj);//如果第二个参数为true,则输出数组 stdClass Object ( [name] => 张飞 [age] => 23 ) Array ( [name] => 张飞 [age] => 23 ) echo '<br>'; //json_encode() 将php中json格式的数组或对象转换成json字符串 print_r(JSON_encode($json_obj));//{"name":"\u5f20\u98de","age":23} 中文被加密乱码 echo '<br>'; /** 中文不乱码的两种方法 **/ print_r(JSON_encode($json_obj,JSON_UNESCAPED_UNICODE));//{"name":"张飞","age":23} print_r(urldecode(JSON_encode($json_obj)));//{"name":"张飞","age":23}
本站提供各类电子书下载,有需求可联系站长。微信:guizhen998. WhatsApp:https://wa.me/14422221313