有什么方法可以用编码 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:12:31  来源:igfitidea点击:

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

phpunicodejson

提问by Binyamin

Any way to return PHP json_encodewith 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_encodedoes have the JSON_UNESCAPED_UNICODEoption 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

This function found here, works fine for me

这个功能在这里找到,对我来说很好用

function jsonRemoveUnicodeSequences($struct) {
   return preg_replace("/\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U')))", json_encode($struct));
}

回答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_UNICODEinside 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 $arrwith $string.

你必须用 替换你$arr$string

I think it will work...try this.

我认为它会起作用……试试这个。