PHP json_encode函数中需要注意的地方php
PHP json_encode函数中需要注意的地方...
在php中使用 json_encode() 内置函数可以使用得php中的数据更好的与其它语言传递与使用。
这个函数的功能是将数组转换成json数据存储格式:
<?php $arr=array('name'=>'Balla_兔子','age'=>22); echo json_encode($arr); ?>
输出结果:
{"name":"","age":22}
json_encode函数中中文被编码成null了,查了下资料,很简单,为了与前端紧密结合,json只支持utf-8编码。
我们可以用iconv函数转换下编码:
string iconv ( string $in_charset , string $out_charset , string $str ) Performs a character set conversion on the string str from in_charset to out_charset.//从in_charset编码转为out_charset,str为转换内容
<?php $arr=array('name'=>iconv('gbk', 'utf-8', 'Balla_兔子'),'age'=>22); echo json_encode($arr); ?>
输出结果:
{"name":"Balla_\u934f\u65bf\u74d9","age":22}
在数组里所有中文在json_encode之后都不见了或者出现\u934f\u65bf\等。
解决方法是用urlencode()函数处理下,在json_encode之前,把所有数组内所有内容都用urlencode()处理,然用json_encode()转换成json字符串,最后再用urldecode()将编码过的中文转回来。
string urlencode ( string $str ) //UrlEncode:将字符串以URL编码返回 返回值:字符串
<?php $arr=array('name'=>urlencode('Balla_兔子'),'age'=>22); $json=json_encode($arr); $result=json_decode($json,true);//把json解码并转为数组 echo urldecode($result['name']); ?>
输出结果:
Balla_兔子
最新评论
热门推荐
我要评论