douding6266 2011-07-21 06:08
浏览 80
已采纳

有没有办法返回PHP`json_encode`编码UTF-8而不是Unicode?

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

$arr=array('a'=>'á');
echo json_encode($arr);

mb_internal_encoding('UTF-8');and $arr=array_map('utf8_encode',$arr); does not fix it.

Result: {"a":"\u00e1"}

Expected result: {"a":"á"}

  • 写回答

5条回答 默认 最新

  • dongluojiao6322 2011-07-21 06:12
    关注

    {"a":"\u00e1"} and {"a":"á"} are different ways to write the same JSON document; The JSON decoder will decode the unicode escape.

    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's JSON encoder and remove line 349 to 433.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • douhutongvm382381 2012-11-20 17:38
    关注

    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;

    The result is a .json file encoded to ANSI as UTF-8.

    评论
  • dpizd08264 2013-06-03 14:07
    关注

    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$1')))", json_encode($struct));
    }
    
    评论
  • duan_88598 2015-07-28 07:09
    关注

    just use this,

    utf8_encode($string);
    

    you've to replace your $arr with $string.

    I think it will work...try this.

    评论
  • dqys98341 2015-08-06 12:55
    关注

    Use JSON_UNESCAPED_UNICODE inside json_encode() if your php version >=5.4.

    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 win11安卓子系统打开谷歌登录不了切使用浏览器显示处于离线状态
  • ¥15 三维直角坐标系下,给定一个平面内四个点坐标,如何将四个点逆时针排序
  • ¥15 UnityWebRequest访问内网地址502
  • ¥20 Python语言来实现牛顿法(Newton's Method)解决非线性(系统)方程的问题。
  • ¥15 matlab控制工业相机采集图像
  • ¥25 R里做折线图和柱状图
  • ¥20 使用kokkos移植项目,遇到问题
  • ¥15 求该问题的Matlab代码
  • ¥15 python下使用pdpbox为何提示has no attribute 'pdp_isolate'?
  • ¥15 求java web病房管理系统项目,用netbeans做的