php中json_encode中文编码问题
在使用Ajax与后台php页面进行交互的时候碰到过中文乱码的问题。
需要传给前台的php数组输出为
Array ( [0] => Array ( [0] => Array ( [0] => 10.0.73.18 ) [1] => Array ( [0] => 10.0.73.19 ) [2] => Array ( [0] => 10.0.73.22 ) ) [1] => Array ( [0] => <thead><tr><th field='id'><center>序号</center></th><th field='domain'><center>域IP</center></th><th field='operate'><center>操作</center></th><thead> ) )
print_r(json_encode($data_head))转换后输出:
[[["10.0.73.18"],["10.0.73.19"],["10.0.73.22"]],[null]]
可以看到汉字没有被转义都为null,这是因为jjson_encode只支持UTF8编码的字符,否则,中文乱码或者空值就出现了,故上面语句应该先转换编码。
Step1
保证在使用JSON处理的时候字符是以UTF8编码的。具体我们可以把数据库编码和页面编码都改为UTF8。当然喜欢用gbk编码的话,可以在进行JSON处理前,把字符转为UTF8形式。在PHP中有如下方法:
$g_personThead=iconv("GB2312","UTF-8//IGNORE",$g_personThead);
Step2
后台PHP页面(页面编码为UTF-8或者已经把字符转为UTF-8)使用json_encode将PHP中的array数组转为JSON字符串。
$g_personThead = urlencode ( $g_personThead );
Step3
输出结果的时候在用函数urldecode()转回来
echo urldecode ( json_encode ( $g_personThead ) );
***
若出现如下报错:
iconv() expects parameter 1 to be string, array given in D:\\Apache Software Foundation\\Apache2.2\\htdocs\\json_test.php on line 19
BUG原因:iconv传入的参数应该是个字符串而不是数组。