Home > Backend Development > PHP Tutorial > Solution to json_encode in php being incompatible with JSON_UNESCAPED_UNICODE, jsonencodeunicode_PHP tutorial

Solution to json_encode in php being incompatible with JSON_UNESCAPED_UNICODE, jsonencodeunicode_PHP tutorial

WBOY
Release: 2016-07-12 08:50:53
Original
885 people have browsed it

php中json_encode不兼容JSON_UNESCAPED_UNICODE的解决方案,jsonencodeunicode

PHP5.4才支持JSON_UNESCAPED_UNICODE这个参数,此参数是让中文字符在json_encode的时候不用转义,减少数据传输量。但在PHP5.3中,就得自己写个函数来实现,以下就是解决方法:

/**
* 对变量进行 JSON 编码
* @param mixed value 待编码的 value ,除了resource 类型之外,可以为任何数据类型,该函数只能接受 UTF-8 编码的数据
* @return string 返回 value 值的 JSON 形式
*/
function json_encode_ex($value)
{
 if (version_compare(PHP_VERSION,'5.4.0','<'))
 {
  $str = json_encode($value);
  $str = preg_replace_callback(
         "#\\\u([0-9a-f]{4})#i",
         function($matchs)
         {
           return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
         },
          $str
         );
  return $str;
 }
 else
 {
  return json_encode($value, JSON_UNESCAPED_UNICODE);
 }
}
Copy after login

判断PHP的版本,如果低于5.4则使用自定义函数来实现,如果是5.4及以上版本则使用JSON_UNESCAPED_UNICODE。

以上就是php中json_encode不兼容JSON_UNESCAPED_UNICODE的解决方案 ,希望能给大家一个参考,了解更多PHP的语法,大家可以关注《PHP5在线手册》,也希望大家多多支持帮客之家。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1133040.htmlTechArticlephp中json_encode不兼容JSON_UNESCAPED_UNICODE的解决方案,jsonencodeunicode PHP5.4才支持JSON_UNESCAPED_UNICODE这个参数,此参数是让中文字符在json_encode的时...
Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template