在 php 中使用 json_encode() 内置函数(php > 5.2)可以使用得 php 中数据可以与其它语言很好的传递并且使用它。这个函数的功能是将数值转换成json数据存储格式,但是转换后的中文会变成Unicode编码。
$arr = array
(
'Name'=>'希亚',
'Age'=>20
);
$jsonencode = json_encode($arr);
echo $jsonencode;
程序运行结果如下:
{“Name”:null,”Age”:20}
json_encode 函数中中文被编码成 null 了,Google 了一下,很简单,为了与前端紧密结合,Json 只支持 utf-8 编码,我认为是前端的 Javascript 也是 utf-8 的原因。
解决方法是用urlencode()函数处理以下,在json_encode 之前,把所有数组内所有内容都用urlencode()处理一下,然用json_encode()转换成json字符串,最后再用urldecode() 将编码过的中文转回来。