PHP5.4开始 json对中文的支持
<?php
$code = 220;
$message = '测试游戏啊!';
$data = [1, 2, 3, 3, 4, 4, 7];
$test_data = ['code' => $code, 'message' => $message, 'data' => $data];
$test_0 = json_encode($test_data);
$test_1 = json_encode($test_data, JSON_UNESCAPED_UNICODE);
$test_2 = json_encode($test_data, JSON_PRETTY_PRINT);
$test_3 = json_encode($test_data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo "<pre>";
print_r($test_0);
echo '<hr>';
print_r($test_1);
echo '<hr>';
print_r($test_2);
echo '<hr>';
print_r($test_3);
echo "</pre>";
exit;
json_encode不转义斜线,不转义中文:
json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
由于 json_encode 和 json_decode只支持utf-8编码的字符,GBK的字符要用json就得转换一下,附自己写的GBK转UTF-8的代码:
/*
字符串GBK转码为UTF-8,数字转换为数字。
*/
function ct2($s){
if(is_numeric($s)) {
return intval($s);
} else {
return iconv("GBK","UTF-8",$s);
}
}
/*
批量处理gbk->utf-8
*/
function icon_to_utf8($s) {
if(is_array($s)) {
foreach($s as $key => $val) {
$s[$key] = icon_to_utf8($val);
}
} else {
$s = ct2($s);
}
return $s;
}
echo json_encode(icon_to_utf8("厦门"));