例如:
复制代码 代码如下:
<?php
$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分钟一班,客满随时发车',
);
/*
通过常规则的json_encode|json_decode来编解码
[""u5927u8fdeu5468u6c34u5b50u673au573a"u2192u4ebau6c11u8def","u8fd0u8425u65f6
u95f4uff1a5uff1a10uff5e21uff1a00 u7968u4ef7uff1a16u5143 u53d1u8f66u95f4u969420
u5206u949fu4e00u73eduff0cu5ba2u6ee1u968fu65f6u53d1u8f66"]
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更懂中文!
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!