首页 > IT职业 > IT图书 > PHP - json_encode中文乱码
调用json_encode()函数将JSON对象转换为字符串, 如果其中包含有中文,默认会输出为unicode编码,如u8023。
解决方案1:
升级到PHP 5.4,在json_encode()函数中,第二个参数指定JSON_UNESCAPED_UNICODE即可。
解决方案2:
对于低版本PHP,对unicode码再进行解码,解码函数如下:
|
function decodeUnicode($str) { return preg_replace_callback('/\\u([0-9a-f]{4})/i', create_function( '$matches', 'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");' ), $str); } |
例子如下:
|
$arr = array('name1':"中文",'name2':'abc12'); $jsonstr = decodeUnicode(json_encode($arr)); |
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3657/viewspace-2809871/ ,如需转载,请注明出处,否则将追究法律责任。