有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP `json_encode`?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6771938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?
提问by Binyamin
Any way to return PHP json_encode
with encode UTF-8 and not Unicode?
有什么方法可以json_encode
用编码 UTF-8 而不是 Unicode返回 PHP ?
$arr=array('a'=>'á');
echo json_encode($arr);
mb_internal_encoding('UTF-8');
and $arr=array_map('utf8_encode',$arr);
does not fix it.
mb_internal_encoding('UTF-8');
并$arr=array_map('utf8_encode',$arr);
没有修复它。
Result: {"a":"\u00e1"}
结果: {"a":"\u00e1"}
Expected result: {"a":"á"}
预期结果: {"a":"á"}
回答by phihag
{"a":"\u00e1"}
and {"a":"á"}
are different ways to write the same JSON document; The JSON decoder will decode the unicode escape.
{"a":"\u00e1"}
并且{"a":"á"}
是编写相同 JSON 文档的不同方式;JSON 解码器将解码 unicode 转义。
In php 5.4+, php's json_encode
does have the JSON_UNESCAPED_UNICODE
option for plain output. On older php versions, you can roll out your own JSON encoder that does not encode non-ASCII characters, or use Pear'sJSON encoder and remove line 349 to 433.
在 php 5.4+ 中,phpjson_encode
确实有JSON_UNESCAPED_UNICODE
纯输出选项。在较旧的 php 版本上,您可以推出自己的不编码非 ASCII 字符的JSON 编码器,或使用Pear 的JSON 编码器并删除第 349 至 433 行。
回答by antoniom
回答by Sheyla Fernandes
I resolved my problem doing this:
我这样做解决了我的问题:
- The .php file is encoded to ANSI. In this file is the function to create the .json file.
- I use
json_encode($array, JSON_UNESCAPED_UNICODE)
to encode the data;
- .php 文件被编码为 ANSI。在这个文件中是创建 .json 文件的函数。
- 我
json_encode($array, JSON_UNESCAPED_UNICODE)
用来编码数据;
The result is a .json file encoded to ANSI as UTF-8.
结果是一个 .json 文件,编码为 ANSI 为 UTF-8。
回答by Lakin Mohapatra
Use JSON_UNESCAPED_UNICODE
inside json_encode()
if your php version >=5.4.
如果您的 php 版本 >=5.4,请JSON_UNESCAPED_UNICODE
在里面使用json_encode()
。
回答by Ashish Tikarye
just use this,
就用这个
utf8_encode($string);
you've to replace your $arr
with $string
.
你必须用 替换你$arr
的$string
。
I think it will work...try this.
我认为它会起作用……试试这个。