Home > Backend Development > PHP Tutorial > Using json_encode to process Chinese in PHP

Using json_encode to process Chinese in PHP

WBOY
Release: 2016-07-30 13:31:08
Original
1431 people have browsed it

用PHP的json_encode来处理中文的时候, 中文都会被编码, 变成不可读的, 类似”\u***”的格式, 还会在一定程度上增加传输的数据量。

<code><span><span><?php</span><span>echo</span> json_encode(<span>"中文"</span>);

<span>//"\u4e2d\u6587"</span></span></code>
Copy after login

在PHP5.4之前的版本,我们只能通过编写函数实现:

<code><span><span>function</span><span>json_encode_cn</span><span>(<span>$data</span>)</span> {</span><span>$data</span> = json_encode ( <span>$data</span> );
        <span>return</span> preg_replace ( <span>"/\\\u([0-9a-f]{4})/ie"</span>, <span>"iconv('UCS-2BE', 'UTF-8', pack('H*', '$1'));"</span>, <span>$data</span> );
    }</code>
Copy after login

而PHP5.4之后,Json新增了一个选项: JSON_UNESCAPED_UNICODE,故名思议,就是说Json不要编码Unicode:

<code><span><span><?php</span><span>echo</span> json_encode(<span>"中文"</span>, JSON_UNESCAPED_UNICODE);

<span>//"中文"</span></span></code>
Copy after login

版权声明:本文为博主原创文章,未经博主允许不得转载。

以上就介绍了PHP中使用json_encode处理中文,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

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