|
转自:http://www.liaoxiaoqi.com/?p=451
注意,这里说的都是基于文本均为utf8格式的前提下,如果不是的话需要先进行转换。
在用PHP提供的json_encode进行转换时,如果遇到中文,就会被直接转换为utf8编码,形如“\u34ab\u9234\u43c1”,网上有人介绍的使用正则替换的方法来解决这个问题,如下:
1.[color=#000000!important][size=1em]functionencode($code)
2.[color=#000000!important][size=1em]{
3.[color=#000000!important][size=1em]$code=json_encode($code);
4.[color=#000000!important][size=1em]returnpreg_replace("#\\\u([0-9a-f]+)#ie","iconv('UCS-2','UTF-8', pack('H4', '\\1'))",$code);
5.[color=#000000!important][size=1em]}
functiondecode($code) {return json_decode($code);}
但是此方法在一些服务器环境,如Linux+Lighttpd等情况下,可能出现无法转换而导致乱码的情况。经过摸索,现提供比较具有通用性的做法是,先将要转换的数组或对象中的中文进行urlencode编码,在完成json转换后,再进行urldecode解码。具体如下:
01.[color=#000000!important][size=1em]functionmyjson($code)
02.[color=#000000!important][size=1em]{
03.[color=#000000!important][size=1em]$code=json_encode(urlencodeAry($code));
04.[color=#000000!important][size=1em]returnurldecode($code);
05.[color=#000000!important][size=1em]}
06.[color=#000000!important][size=1em]
07.[color=#000000!important][size=1em]functionurlencodeAry($data)
08.[color=#000000!important][size=1em]{
09.[color=#000000!important][size=1em]if(is_array($data))
10.[color=#000000!important][size=1em]{
11.[color=#000000!important][size=1em]foreach($dataas$key=>$val)
12.[color=#000000!important][size=1em]{
13.[color=#000000!important][size=1em]$data[$key]= urlencodeAry($val);
14.[color=#000000!important][size=1em]}
15.[color=#000000!important][size=1em]return$data;
16.[color=#000000!important][size=1em]}
17.[color=#000000!important][size=1em]else
18.[color=#000000!important][size=1em]{
19.[color=#000000!important][size=1em]returnurlencode($data);
20.[color=#000000!important][size=1em]}
21.[color=#000000!important][size=1em]}
补充:
PHP的strtolower()和strtoupper()函数在安装非中文系统的服务器下可能会导致将汉字转换为乱码,可使用类似的方法进行编解码。 |
|
|