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

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-13 11:40:46
Original
1110 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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template