PHP如何实现json_encode不转义中文。默认情况下,json_encode会把特殊字符进行转义,同时中文也会转义成unicode编码。这样数据库查看数据很蛋疼,我们就需要对中文进行不转义。限制中文的话,json_encode自带一个参数,JSON_UNESCAPED_UNICODE。
json_encode($data,JSON_UNESCAPED_UNICODE);
但是这个参数,只有在php5.4以上(不包括5.4)才支持,对于PHP5.3版本,可以先把ASCII 127以上的字符转换为HTML数值,这样避免被json_decode函数转码:
function my_json_encode($data){ if(PHP_VERSION > '5.4') { return json_encode($data, JSON_UNESCAPED_UNICODE); } else { array_walk_recursive($data, function(&$item, $key) { if(is_string($item)) { $item = mb_encode_numericentity($item, array (0x80, 0xffff, 0, 0xffff), 'UTF-8'); } }); return mb_decode_numericentity(json_encode($data), array (0x80, 0xffff, 0, 0xffff), 'UTF-8'); } }
这样就可以实现json_encode不转义中文。其中mb_decode_numericentity()函数,是根据 HTML 数字字符串解码成字符。