Home > php教程 > php手册 > php中json_encode处理gbk与gb2312中文乱码问题的解决方法,

php中json_encode处理gbk与gb2312中文乱码问题的解决方法,

WBOY
Release: 2016-06-13 09:29:16
Original
1636 people have browsed it

php中json_encode处理gbk与gb2312中文乱码问题的解决方法,

本文讲述了php中json_encode处理gbk与gb2312中文乱码问题的解决方法,具体方法如下:

1.json_encode()中文在gbk/gb2312中对中文返回为null

$arr = array ( 
 array ( 
   'catid' => '4', 
   'catname' => 'www.jb51.net', 
   'meta_title' => '帮客之家' 
  )
);
 
echo json_encode($arr);
Copy after login

运行结果:

[{"catid":"4","catname":"www.jb51.net","meta_title":null}]
Copy after login

  看一了吗"meta_title":null 他本来是有一个值的为"帮客之家"了,这个我们查了一下原理是json_encode只支持uft-8编码,我们转换一下

<&#63;php
$data="JSON中文";
$newData=iconv("GB2312″,"UTF-8//IGNORE",$data);
echo $newData;
//ignore的意思是忽略转换时的错误,如果没有ignore参数,所有该字符后面的字符都不会被保存。
//或是("GB2312″,"UTF-8″,$data);
&#63;>
Copy after login

2.后台PHP页面(页面编码为UTF-8或者已经把字符转为UTF-8)使用json_encode将PHP中的array数组转为JSON字符串。例如:

<&#63;php
$testJSON=array('name'=>'中文字符串','value'=>'test');
echo json_encode($testJSON);
&#63;>
Copy after login

查看输出结果为:

{"name":"u4e2du6587u5b57u7b26u4e32″,"value":"test"}

Copy after login

  可见即使用UTF8编码的字符,使用json_encode也出现了中文乱码。解决办法是在使用json_encode之前把字符用函数urlencode()处理一下,然后再json_encode,输出结果的时候再用函数urldecode()转回来。具体如下:

<&#63;php
$testJSON=array('name'=>'中文字符串','value'=>'test');
//echo json_encode($testJSON);
foreach ( $testJSON as $key => $value ) {
$testJSON[$key] = urlencode ( $value );
}
echo urldecode ( json_encode ( $testJSON ) );
&#63;>
Copy after login

查看输出结果为:

{"name":"中文字符串","value":"test"}

Copy after login

  总结:json_encode函数只能处理uft8字符串,如果是中文估计是对字节处理不好,因为中文gbk与uft长度是不一样的,这个也不做深入介绍了。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template