简体   繁体   English

PHP响应中的文本编码

[英]text encoding in php response

i'm trying to print a JSON in Hebrew and only get utf-8 encoded string. 我正在尝试在希伯来语中打印JSON,并且仅获取utf-8编码的字符串。 how can I make sure the client's browser shows the string in Hebrew? 如何确保客户端的浏览器在希伯来语中显示字符串?

the code is: 代码是:

<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>

and the response is: 响应是:

{{"stores":[{"_id":"1","name":"\ח\ת\ו\ל\י","store_type":"\מ\ס\ע\ד\ת \ב\ש\ר\י\ם"},{"_id":"2","name":"\מ\ע\ד\נ\י \מ\א\מ\י","store_type":"\מ\ס\ע\ד\ה \ל\ר\ו\ס\י\ם"}],"success":1 {{“ stores”:[{“ _ id”:“ 1”,“ name”:“ \\ u05d7 \\ u05ea \\ u05d5 \\ u05dc \\ u05d9”,“ store_type”:“ \\ u05de \\ u05e1 \\ u05e2 \\ u05d3 \\ u05ea \\ u05d1 \\ u05e9 \\ u05e8 \\ u05d9 \\ u05dd“},{” _ id“:” 2“,”名称“:” \\ u05de \\ u05e2 \\ u05d3 \\ u05e0 \\ u05d9 \\ u05de \\ u05d0 \\ u05de \\ u05d9“,” store_type“:” \\ u05de \\ u05e1 \\ u05e2 \\ u05d3 \\ u05d4 \\ u05dc \\ u05e8 \\ u05d5 \\ u05e1 \\ u05d9 \\ u05dd“}”,“成功”:1

A nice constant was added in PHP 5.4: JSON_UNESCAPED_UNICODE PHP 5.4中添加了一个不错的常量: JSON_UNESCAPED_UNICODE

Using it will not escape your Hebrew characters. 使用它不会逃避希伯来语字符。

echo json_encode($response, JSON_UNESCAPED_UNICODE);

Check out the json_encode reference . 查看json_encode参考

The result looks like a UCS-2 string. 结果看起来像UCS-2字符串。 Try setting the charset of the Mysql Connection: 尝试设置Mysql连接的字符集:

mysql_set_charset('utf8', $conn)

then remove the utf8_encode statements 然后删除utf8_encode语句

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM