0
点赞
收藏
分享

微信扫一扫

让Json更懂中文(JSON_UNESCAPED_UNICODE)

hwwjian 2022-04-02 阅读 74
phpjsonico

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

<?php
echo json_encode('中文');
//"\u4e2d\u6587"

这就让我们这些在天朝做开发的同学, 很是头疼, 有的时候还不得不自己写json_encode.

而在PHP5.4, 这个问题终于得以解决, Json新增了一个选项: JSON_UNESCAPED_UNICODE, 故名思议, 就是说, Json不要编码Unicode.

看下面的例子:

<?php
echo json_encode('中文', JSON_UNESCAPED_UNICODE);
//"中文"

怎么样, 是不是让大家很开心的改动? 呵呵, 当然, Json在5.4还加入了: JSON_BIGINT_AS_STRING, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES等选项, 如果有兴趣, 大家可以参看: json_encode

下列常量由此扩展定义,且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

以下常量表示了 json_last_error() 所返回的错误类型。

JSON_ERROR_NONE​ (integer)

没有错误发生。自 PHP 5.3.0 起生效。 JSON_ERROR_DEPTH​ (integer)

到达了最大堆栈深度。自 PHP 5.3.0 起生效。 JSON_ERROR_STATE_MISMATCH​ (integer)

出现了下溢(underflow)或者模式不匹配。自 PHP 5.3.0 起生效。 JSON_ERROR_CTRL_CHAR​ (integer)

控制字符错误,可能是编码不对。自 PHP 5.3.0 起生效。 JSON_ERROR_SYNTAX​ (integer)

语法错误。 自 PHP 5.3.0 起生效。 JSON_ERROR_UTF8​ (integer)

异常的 UTF-8 字符,也许是因为不正确的编码。 此常量自 PHP 5.3.3 起生效。 JSON_ERROR_RECURSION​ (integer)

The object or array passed to json_encode()​ include recursive references and cannot be encoded. If theJSON_PARTIAL_OUTPUT_ON_ERROR​ option was given, NULL will be encoded in the place of the recursive reference.

This constant is available as of PHP 5.5.0.

JSON_ERROR_INF_OR_NAN​ (integer)

The value passed to json_encode()​ includes either NAN or INF. If the JSON_PARTIAL_OUTPUT_ON_ERRORoption was given, ​0​ will be encoded in the place of these special numbers.

This constant is available as of PHP 5.5.0.

JSON_ERROR_UNSUPPORTED_TYPE​ (integer)

A value of an unsupported type was given to json_encode()​, such as a resource​. If theJSON_PARTIAL_OUTPUT_ON_ERROR​ option was given, NULL will be encoded in the place of the unsupported value.

This constant is available as of PHP 5.5.0.

下面的常量可以和 json_encode() 的 form 选项结合使用。

JSON_HEX_TAG​ (integer)

所有的 < 和 > 转换成 \u003C 和 \u003E。 自 PHP 5.3.0 起生效。 JSON_HEX_AMP​ (integer)

所有的 & 转换成 \u0026。 自 PHP 5.3.0 起生效。 JSON_HEX_APOS​ (integer)

所有的 ' 转换成 \u0027。 自 PHP 5.3.0 起生效。 JSON_HEX_QUOT​ (integer)

所有的 " 转换成 \u0022。 自 PHP 5.3.0 起生效。 JSON_FORCE_OBJECT​ (integer)

使一个非关联数组输出一个类(Object)而非数组。 在数组为空而接受者需要一个类(Object)的时候尤其有用。 自 PHP 5.3.0 起生效。 JSON_NUMERIC_CHECK​ (integer)

将所有数字字符串编码成数字(numbers)。 自 PHP 5.3.3 起生效。 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 起生效。

举报

相关推荐

0 条评论