Home > Backend Development > PHP Tutorial > PHP5.4中json_encode中文转码的变化小结_php技巧

PHP5.4中json_encode中文转码的变化小结_php技巧

WBOY
Release: 2016-05-17 09:06:57
Original
1123 people have browsed it

在php5.4以前做json_encode的时候中文会被unicode编码,中文都会被编码,变成不可读的,类似“u***”的格式,还会在一定程度上增加传输的数据量。
例如:

复制代码 代码如下:

$str = '中文';
echo json_encode($str);
//"\u4e2d\u6587"
php5.4开始
echo json_encode($str, JSON_UNESCAPED_UNICODE);
//"中文"

php5.4让json更懂中文!
5.4之前不进行unicode转码,有3种方法处理
但其实前两种方式是会导致问题,在一些特殊的情况下。如下例:
复制代码 代码如下:

function myjson($code) {
$code = json_encode(urlencodeAry($code));
return urldecode($code);
}
function urlencodeAry($data) {
if(is_array($data)) {
foreach($data as $key=>$val) {
$data[$key] = urlencodeAry($val);
}
return $data;
} else {
return urlencode($data);
}
}
$test = array (
0 => '"大连周水子机场"→人民路',
1 => '运营时间:5:10~21:00 票价:16元 发车间隔20分钟一班,客满随时发车',
);
/*
通过常规则的json_encode|json_decode来编解码
["\"\u5927\u8fde\u5468\u6c34\u5b50\u673a\u573a\"\u2192\u4eba\u6c11\u8def","\u8fd0\u8425\u65f6
\u95f4\uff1a5\uff1a10\uff5e21\uff1a00 \u7968\u4ef7\uff1a16\u5143 \u53d1\u8f66\u95f4\u969420
\u5206\u949f\u4e00\u73ed\uff0c\u5ba2\u6ee1\u968f\u65f6\u53d1\u8f66"]
array (
0 => '"大连周水子机场"→人民路',
1 => '运营时间:5:10~21:00 票价:16元 发车间隔20分钟一班,客满随时发车',
)
*/
$test1 = json_encode($test);
$test2 = json_decode($test1, TRUE);
echo $test1;
echo PHP_EOL;
var_export($test2);
echo PHP_EOL;
/*
通过myjson|json_decode来编解码,但是会出报错json_last_error返回(JSON_ERROR_SYNTAX === 4),
因为""大连周水子机场"→人民路"
[""大连周水子机场"→人民路","运营时间:5:10~21:00 票价:16元 发车间隔20分钟一班,客满随时发车"]
NULL
*/
$test1_1 = myjson($test);
$test2_1 = json_decode($test1_1, TRUE);
echo $test1_1;
echo PHP_EOL;
var_export($test2_1);
echo PHP_EOL;
/*
通过json_enco+pack|json_decode来编解码,保证不会对中文编码,但是会缺少运营时间数据和票价
["\"大连周水子机场\"→人民路","运营时间::~: 票价:元 发车间隔分钟一班,客满随时发车"]
array (
0 => '"大连周水子机场"→人民路',
1 => '运营时间::~: 票价:元 发车间隔分钟一班,客满随时发车',
)
*/
function replaceUni($str) {
return preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $str);
}
$test1_2 = replaceUni(json_encode($test));
$test2_2 = json_decode($test1_2, TRUE);
echo $test1_2;
echo PHP_EOL;
var_export($test2_2);
echo PHP_EOL;

最后总结一句,推荐升级到PHP5.4,让PHP更懂中文!
Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template