
json 转码问答
在使用 php 将数组转换为 json 时,如果数组中包含中文数据,可能会遇到中文乱码的问题。
问题描述
以下 php 代码尝试将包含中文数据的数组转换为 json,但输出中中文出现了乱码:
立即学习“PHP免费学习笔记(深入)”;
<?php
if($result1) {
$users=array();
$i=0;
while($row=mysql_fetch_array($result1,mysql_assoc)) {
$users[$i]=$row;
$i++;
}
echo json_encode(array("result" => "success", "countall" => $roa[0], "data" => $users));
} else {
echo json_encode(array("result" => "fail"));
}
?>输出结果:
{"result":"success","countall":"2","data":[{"id":"1","openid":"1","name":"\u53bb","phone":"1","status":"1","checkcode":"1"},{"id":"2","openid":"1","name":"\u6211","phone":"12","status":"1","checkcode":"12"}]}其中,"name" 值出现了乱码,如 "名" 显示为 "u53bb"。
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
原因
"name" 值使用 utf-8 编码存储在数据库中,而 php 的 json_encode 函数默认使用 ascii 编码将数据转换为 json。这会导致中文数据在转换过程中乱码。
解决方法
要解决中文乱码问题,需要在 json_encode 函数中指定要使用的编码。可以在函数参数中添加第二个参数,如下所示:
echo json_encode(array("result" => "success", "countall" => $roa[0], "data" => $users), json_unescaped_unicode);或者,可以在 php 配置文件中设置 json_encode.options 选项,如下所示:
json_encode.options = JSON_UNESCAPED_UNICODE
这样,php 就会将中文数据以 utf-8 编码转换为 json,从而解决中文乱码问题。
以上就是PHP 数组转 JSON 时,中文乱码怎么办?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号