简单程序员首页投稿(暂停使用,暂停投稿)

读懂json_encode([$array], JSON_UNE

2016-06-07  本文已影响352人  西贝巴巴

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

<pre>
echo json_encode("中文");
//"\u4e2d\u6587"
</pre>

       这就让我们这些在天朝做开发的同学, 很是头疼, 有的时候还不得不自己写json_encode.
而在PHP5.4, 这个问题终于得以解决, Json新增了一个选项: JSON_UNESCAPED_UNICODE, 故名思议, 就是说, Json不要编码Unicode.

看下面的例子:

<pre>
echo json_encode("中文", JSON_UNESCAPED_UNICODE);
//"中文"
</pre>

还有:

**JSON_BIGINT_AS_STRING
** (integer)
将大数字编码成原始字符原来的值。 自 PHP 5.4.0 起生效。
**JSON_PRETTY_PRINT
** (integer)
用空白字符格式化返回的数据。 自 PHP 5.4.0 起生效。
**JSON_UNESCAPED_SLASHES
** (integer)
不要编码 /。 自 PHP 5.4.0 起生效。
**JSON_UNESCAPED_UNICODE
** (integer)
以字面编码多字节 Unicode 字符(默认是编码成 \uXXXX)。 自 PHP 5.4.0 起生效。
在写接口的时候我们也会用到:

<pre>
function ajaxReturn($status, $data, $note) {
echo json_encode(['status' => (int) $status, 'data' => $data, 'note' => $note], JSON_UNESCAPED_UNICODE);
die();
}
</pre>

20160607155646.png
上一篇下一篇

猜你喜欢

热点阅读