PHP输出JSON Web Service charset UTF-8错误

Don*_*Den 5 php encoding json web-services hebrew

我正在通过PHP托管JSON输出的Web服务.

我在DB中有希伯来语数据集,我将此作为输出发布到Web服务.

当我最初发布数据时,它输出结果如下:

JSON:

{
    "tasklist": [
        {
            "customerID": "9936",
            "name": "טר ×רמה ×™×–×•× ×•×‘×™× ×•×™ בע"מ",
            "cargo":"×ברר",
            "destination":"מכר", 
            "quantity":"1.000000",
            "startdate":"03/01/201300: 00: 00" 
        }
               ]
}
Run Code Online (Sandbox Code Playgroud)

但这"×ברר"可以通过Android/Iphone解析器读取并将其转换为原始希伯来语.但我遇到了错误 "name": "טר ×רמה ×™×–×•× ×•×‘×™× ×•×™ בע"מ",.其中,"在字符串之间,因此JSON是无效的,并显示错误!

在此输入图像描述

为了解决这个问题我曾经UTF-8把它转换"×ברר"成希伯来语"????".但在这种情况下,问题仍然存在:

PHP:

header('Content-type:text/html; charset = UTF-8');

JSON:

{
    "tasklist": [
        {
            "customerID": "9936",
            "name": "?? ???? ???? ?????? ??"?",
            "cargo":"????",
            "destination":"???",
            "quantity":"1.000000",
            "startdate":"03/01/201300: 00: 00"
        }
                ]
}
Run Code Online (Sandbox Code Playgroud)

但问题仍然存在:

在此输入图像描述

在某些情况下,?由于使用UTF-8,我得到了这个

"name":"?????? ??? ?????-????? ??"
Run Code Online (Sandbox Code Playgroud)
  • 我怎样才能克服这个问题?
  • 我需要使用其他特定的编码吗?

注意:数据不能在数据库中更改解决方案应该在输出到JSON时.

DB中存储的数据如何显示如下:

名称

×ž× - ×|×'ות×>פ׬לע×"×™ - × - ומ׬ימ×

我的PHP脚本输出JSON:

<?php

//My DB connection and Query comes here

$jsontext = '{"tasklist":[';
while($row = mysql_fetch_array($queryExe)){
$jsontext .= '{"customerID":"'.$row['AUTO_ID'].'",';
$jsontext .='"name":"'.$row['Customer_Name'].'",';
$jsontext .='"cargo":"'.$row['Type_of_Cargo'].'",';
$jsontext .='"destination":"'.$row['Destination'].'",';
$jsontext .='"quantity":"'.$row['Quantity'].'",';
$jsontext .='"startdate":"'.$row['startdate'].'"},';
}
$jsontext = substr_replace($jsontext, '', -1); // to get rid of extra comma
$jsontext .= "]}";

header('Content-type: text/html; charset=UTF-8');

//Output the final JSON
echo $jsontext;

?>
Run Code Online (Sandbox Code Playgroud)

提前谢谢你的帮助!

问题清楚了吗?了解我的问题.

ste*_*ven 15

如果你的db-field是utf8,你应该坚持:

mysql_query("SET NAMES 'utf8'");
Run Code Online (Sandbox Code Playgroud)

在插入数据之前,您应该始终执行'SET NAMES ...'.确保你真的存储了utf8编码的字符串!

那么你的查询:

mysql_query($your_query);

$array = array("tasklist"=>array());    

while($row = mysql_fetch_array($queryExe)){
        $a = array();
        $a["customerID"] = $row['AUTO_ID'];
        $a["name"] = $row['Customer_Name'];
        $a["cargo"] = $row['Type_of_Cargo'];
        $a["destination"] = $row['Destination'];
        $a["quantity"] = $row['Quantity'];
        $a["startdate"] = $row['startdate'];
        $array["tasklist"][] = $a;
}

header("Content-type: application/json; charset=utf-8");

echo json_encode($array);
exit();
Run Code Online (Sandbox Code Playgroud)

当服务器默认字符集例如是iso时,我已经获得了这些还不够的经验.在这种情况下,我需要在我的.htaccess中执行以下操作:

AddDefaultCharset utf-8
Run Code Online (Sandbox Code Playgroud)