Home  >  Article  >  Backend Development  >  Regarding PHP json_decode Chinese escaping issues

Regarding PHP json_decode Chinese escaping issues

藏色散人
藏色散人Original
2020-10-09 11:10:453050browse

php json decode转义的使用方法:首先使用语句“json_encode($a, JSON_UNESCAPED_UNICODE);”把特殊字符进行转义;然后通过该函数的第二个参数限制转义范围即可。

Regarding PHP json_decode Chinese escaping issues

推荐:《PHP视频教程》 

PHP json_decode中文转义的问题

默认情况下PHP的 json_decode 方法会把特殊字符进行转义,还会把中文转为Unicode编码形式。在有些情况下不希望进行这种转义。

对于PHP5.4+版本,json_decode函数第二个参数,可以用来限制转义范围。要限制中文,使用JSON_UNESCAPED_UNICODE参数。

json_encode($a, JSON_UNESCAPED_UNICODE);

对于PHP5.3及以前版本,可以用如下方式转回中文:

$originstr = '{"name":"张三"}';
$jsonobject = json_decode($originstr);
// badstr: {"name":"\u5f20\u4e09"}
$badstr = json_encode($jsonobject);
// goodstr: {"name":"张三"} 
$goodstr = preg_replace_callback("#\\\u([0-9a-f]{4})#i", function($matches){
  return iconv('UCS-2', 'UTF-8', pack('H4', $matches[1]));
  }, $badstr);

The above is the detailed content of Regarding PHP json_decode Chinese escaping issues. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn