【问题标题】:text encoding in php responsephp响应中的文本编码
【发布时间】:2013-10-01 23:45:15
【问题描述】:

我正在尝试用希伯来语打印 JSON,并且只获取 utf-8 编码的字符串。如何确保客户端的浏览器以希伯来语显示字符串?

代码是:

<html>
 <head>
  <meta charset=utf-8" />
 </head>
<body>
<?php 
     header('Content-Type: text/html; charset=utf-8');
    $response = array();
    require_once __DIR__.'/db_connect.php';
    $db = new DB_CONNECT();

    $result = mysql_query(" SELECT * FROM stores") or die(mysql_error());

    if (mysql_num_rows($result)>0){
        $response["stores"]=array();

        while($row = mysql_fetch_array($result)){
            $store = array();
            $store["_id"]=$row["_id"];
            $store["name"]=$row["name"];
            $store["store_type"]=$row["store_type"];

            array_push($response["stores"],$store);

        }
        $response["success"] = 1;
        $string =  utf8_encode(json_encode($response));
        echo hebrevc($string);    
    }else{
        $response["success"]=0;
        $response["message"]="No stores found";
        echo utf8_encode(json_encode($response));
    }
    ?>


 </body>
</html>

响应是:

{{"商店":[{"_id":"1","name":"\u05d7\u05ea\u05d5\u05dc\u05d9","store_type":"\u05de\u05e1\u05e2\u05d3\ u05ea \u05d1\u05e9\u05e8\u05d9\u05dd"},{"_id":"2","name":"\u05de\u05e2\u05d3\u05e0\u05d9 \u05de\u05d0\u05de\u05d9","store_type ":"\u05de\u05e1\u05e2\u05d3\u05d4\u05dc\u05e8\u05d5\u05e1\u05d9\u05dd"}],"成功":1

【问题讨论】:

  • 除非您知道您的数据采用 ISO-8859-1 编码,否则请勿使用 utf8_encode() - 这不是灵丹妙药。
  • 您的Content-type 标头最好由服务器设置,但如果您必须使用PHP 发送它,请在任何输出之前进行(即在顶部)。您还错过了charset=utf-8" 上的报价

标签: php json encoding utf-8


【解决方案1】:

在 PHP 5.4 中添加了一个不错的常量:JSON_UNESCAPED_UNICODE

使用它不会逃脱您的希伯来语字符。

echo json_encode($response, JSON_UNESCAPED_UNICODE);

查看json_encode reference。

【讨论】:

    【解决方案2】:

    结果看起来像 UCS-2 字符串。尝试设置 Mysql Connection 的字符集:

    mysql_set_charset('utf8', $conn)
    

    然后删除utf8_encode 语句

    【讨论】:

      猜你喜欢
      • 2013-09-21
      • 2017-06-26
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 2016-10-31
      相关资源
      最近更新 更多