Home >php教程 >php手册 >json_encode如何防止汉字转义成unicode,json_encodeunicode

json_encode如何防止汉字转义成unicode,json_encodeunicode

WBOY
WBOYOriginal
2016-06-13 08:45:411296browse

json_encode如何防止汉字转义成unicode,json_encodeunicode

众所周知,json_encode通常会把json中的汉字转义成unicode,但是这并不一定是我们想要的。有时候,我们需要获得汉字形式的json字符串,比如需要获得gbk编码的json字符串(只要把汉字形式的字符串转码就可以得到了)。有什么好办法么?

php官方听到了这个需求,并提供了一种可靠的解决方案:JSON_UNESCAPED_UNICODE。这个参数可以保证json_encode不再将汉字转为unicode。

似乎这样就解决了?当我们高高兴兴的用这个参数的时候,发现并没有什么卵用。仔细一看,这个参数只有5.4之后的php支持。那更早期的php怎么办呢?

社区提供了一种方案:

<span>1</span> <span>function</span> my_json_encode(<span>$arr</span><span>){
</span><span>2</span>         <span>//</span><span>convmap since 0x80 char codes so it takes all multibyte codes (above ASCII 127). So such characters are being "hidden" from normal json_encoding</span>
<span>3</span>         <span>array_walk_recursive</span>(<span>$arr</span>, <span>function</span> (&<span>$item</span>, <span>$key</span>) { <span>if</span> (<span>is_string</span>(<span>$item</span>)) <span>$item</span> = mb_encode_numericentity(<span>$item</span>, <span>array</span> (0x80, 0xffff, 0, 0xffff), 'UTF-8'<span>); });
</span><span>4</span>         <span>return</span> mb_decode_numericentity(json_encode(<span>$arr</span>), <span>array</span> (0x80, 0xffff, 0, 0xffff), 'UTF-8'<span>);
</span><span>5</span> }

不过这种方法只有5.3才支持,因为5.2并不支持匿名函数。至于解决办法?把匿名函数定义一下即可。

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