Home > php教程 > php手册 > php不转义中文字符的 json编码方法

php不转义中文字符的 json编码方法

WBOY
Release: 2016-06-13 09:33:09
Original
966 people have browsed it

   虽说最新的 PHP 5.4 已经良好支持 JSON 中文编码,即通过 JSON_UNESCAPED_UNICODE 参数,例如:

  json_encode("中文", JSON_UNESCAPED_UNICODE)对于早前 PHP 版本,处理不转义中文字符的 json 编码,之前写过 PHP 输出中文 JSON 字符串这篇文章,这里分享个更完美的方法:

  /**

  * 不转义中文字符的 json 编码方法

  * @param array $arr 待编码数组

  * @return string

  */

  function encode ($arr) {

  $str = json_encode($arr);

  $search = "#\\\u([0-9a-f]+)#ie";

  $replace = "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))";

  return preg_replace($search, $replace, $str);

  }

source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template