Home > php教程 > php手册 > PHP使用json中文乱码解决方法实例讲解

PHP使用json中文乱码解决方法实例讲解

WBOY
Release: 2016-06-13 10:39:49
Original
998 people have browsed it

php中常用的两个函数 encode_json()和decode_json() ;
我们重点说一下encode_json()函数在进行中文编码时出现乱码的解决方法。
首先,我们写出所需要的数组:
$json = array (
0 =>
array (
id => 13,
name => 乒乓球,
),
1 =>
array (
id => 17,
name => 篮球,
)
)
?>

如果我们直接用encode_json进行编码的话,输出结果是:
[{"id":"13","name":null}
,{"id":"13","name":null}]
?>
很明显,中文字符没有编码正确。这是因为json仅仅转义encoding编码,
(假设我们后台文件用的是gb2312编码)故上面语句应该先转换编码:
foreach ($ajax as $key=>$val)
{
$ajax[$key][name] =
urlencode($val[name]);
}
echo json_encode($json);
?>
同理,在客户端js代码中队已经编码的中文进行decodeURI()解码即可。
至此,解决php中json中文编码问题。

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