1.json_encode()中文在gbk/gb2312中对中文返回为null
$arr = array (
array (
'catid' => '4',
'catname' => 'www.genban.org',
'meta_title' => 'genban'
)
);
echo json_encode($arr);
运行结果:
[{"catid":"4","catname":"www.genban.org","meta_title":null}]
看一了吗"meta_title":null 他本来是有一个值的为"genban"了,这个我们查了一下原理是json_encode只支持uft-8编码,我们转换一下
<?php
$data="JSON中文";
$newData=iconv("GB2312″,"UTF-8//IGNORE",$data);
echo $newData;
//ignore的意思是忽略转换时的错误,如果没有ignore参数,所有该字符后面的字符都不会被保存。
//或是("GB2312″,"UTF-8″,$data);
?>
2.后台php页面(页面编码为UTF-8或者已经把字符转为UTF-8)使用json_encode将php中的array数组转为JSON字符串。例如:
<?php
$testJSON=array('name'=>'中文字符串','value'=>'test');
echo json_encode($testJSON);
?>
查看输出结果为:
{"name":"u4e2du6587u5b57u7b26u4e32″,"value":"test"}
可见即使用UTF8编码的字符,使用json_encode也出现了中文乱码。解决办法是在使用json_encode之前把字符用函数urlencode()处理一下,然后再json_encode,输出结果的时候再用函数urldecode()转回来。具体如下:
<?php
$testJSON=array('name'=>'中文字符串','value'=>'test');
//echo json_encode($testJSON);
foreach ( $testJSON as $key => $value ) {
$testJSON[$key] = urlencode ( $value );
}
echo urldecode ( json_encode ( $testJSON ) );
?>
查看输出结果为:
{"name":"中文字符串","value":"test"}
总结:json_encode函数只能处理uft8字符串,如果是中文估计是对字节处理不好,因为中文gbk与uft长度是不一样的,这个也不做深入介绍了。
The End




大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)