我的php web服务使用json_encode返回从MySQL数据库表中获取的json数据。数据应以unicode等本地语言返回。而是像hindi / telugu / bengali这样的本地字符显示为html实体。但输出需要作为unicode和NOT html实体。
<?php
//header('Content-Type: text/html;charset: utf8'); //wasted code line
//Connection and credentials
$servername = "xxx.yyy.zzz.nnn";
$username = "username";
$password = "password";
$dbname = "mydb";
//variables to store fetched data
$item[]=array();
$dataArray[] = array();
// Create connection
$conn = mysql_connect($servername, $username, $password);
//mysql_set_charset('utf8', $conn); //wasted code line
$mytopid = mysql_real_escape_string($_GET['mytopid']); //get input
$query = "SELECT * FROM datamaster where Id > '$mytopid' order by Id desc"; //Now query
//mysql_query("set names 'utf8'"); //wasted code line
if ($result=mysql_query($query,$conn)){
$rows = mysql_numrows($result);
$i= 0;
while ($i < $rows){
//fetch data
$row = mysql_fetch_array($result);
//wasted code lines
//$dataArray[$i]["shortid"] = utf8_encode($row['Id']);
//$dataArray[$i]["shorttitle"] = utf8_encode($row['Title']);
//reality
$dataArray[$i]["shortid"] = $row['Id'];
$dataArray[$i]["shorttitle"] = $row['Title'];
$i++;
}
$item[0]["response"] = 1;
$item[1]["matching"] = $rows;
$item[2]["events"]=$dataArray;
echo json_encode($item);
}else{
$item[0]["response"] = 0;
}
//echo json_encode($item, JSON_HEX_TAG| JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); //wasted code line
mysql_close($conn);
?>
获得输出: Actual Output
所需输出: [{“shortid”:“5”,“shorttitle”:“\ u0c38 \ u0c32 \ u0c4d \ u0c2e \ u0c3e \ u0c28 \ u0c4d \ u200c \ u0c05 \ u0c21 \ u0c3f \ u0c17 \ u0c3f \ u0c28 \ u0c3e \ u0c05 \ u0c35 \ u0c15 \ u0c3e \ u0c36 \ u0c2e \ u0c3f \ u0c35 \ u0c4d \ u0c35 \ u0c32 \ u0c47 \ u0c26 \ u0c41!“}]
我最终将我的客户端程序解码转换为本地语言。 所需的输出应该是json_encode的默认行为。尽管每个php文档都进行了大多数试验(参见显示我的试验//评论代码行的注释CODE行),但输出仍然是html实体,除了英语。
我的客户编程语言不会翻译html实体。
是否有php方式来获取所需的输出? 我已经尝试了堆栈溢出和php文档中的每个可能的概念。现在我需要帮助。
答案 0 :(得分:1)
使用json_encode($item, JSON_UNESCAPED_UNICODE);
。它将逐字编码多字节字符。
您可以获得更多信息here。
实际上,您的客户端无法处理转义字符很奇怪。你到底用了什么?
答案 1 :(得分:0)
请你告诉Wazelin及时回复。我过早地尝试过JSON_UNESCAPED_UNICODE方法。但是那个输出仍然是html实体。
临时修复了我偶然使用html_entity_decode的问题。
我将while循环中的代码行更改为:
while ($i < $rows){
//fetch data
$row = mysql_fetch_array($result);
//reality
$dataArray[$i]["shortid"] = $row['Id'];
//handle html entities of local language
$dataArray[$i]["shorttitle"] = html_entity_decode($row['Title']);
$i++;
}
已经给出了所需的输出。 但对每个Web服务执行此操作并不是一个理想的解决方案。 非常奇怪的是,在我的情况下,默认的json_encode行为非常难以捉摸。
答案 2 :(得分:0)
检查文件: http://php.net/manual/en/function.json-encode.php
有一些选项可以让您正确编码数据。