在php5.4以前做json_encode的时候中文会被unicode编码,中文都会被编码,变成不可读的,类似“u***”的格式,还会在一定程度上增加传输的数据量。
例如:
复制代码 代码如下:
$str = '中文';
echo json_encode($str);
//"u4e2du6587"
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分钟一班,客满随时发车',
);
$test1 = json_encode($test);
$test2 = json_decode($test1, TRUE);
echo $test1;
echo PHP_EOL;
var_export($test2);
echo PHP_EOL;
$test1_1 = myjson($test);
$test2_1 = json_decode($test1_1, TRUE);
echo $test1_1;
echo PHP_EOL;
var_export($test2_1);
echo PHP_EOL;
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更懂中文!



