我的php web服务使用json_encode返回从MySQL数据库表中获取的json数据。数据应该以任何本地语言作为unicode返回。相反,像印地语/泰卢固语/孟加拉语这样的本地字符被显示为html实体。但是输出需要unicode而不是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);
?>
输出:实际产出
要求输出:[{"shortid":"5","shorttitle":"'u0c38'u0c32'u0c4d'u0c2e'u0c3e'u0c28'u0c4d'u200c 'u0c05'u0c21'u0c3f'u0c17' u0c3e' u0c05'u0c35'u0c15'u0c3e' u0c2e'u0c3f'u0c35'u0c4d'u0c35'u0c32' u0c26'u0c41!"}]
我最终在我的客户端程序解码转换成本地语言。所需的输出应该是json_encode的默认行为。尽管大多数试验都是针对php文档(请参阅注释的CODE行,显示我的试验//浪费的代码行),但输出仍然是html实体,除了英语语言。
我的客户端编程语言不翻译html实体。
是否有一个php的方式来获得所需的输出?我已经尝试了所有可能的概念堆栈溢出和php文档。现在我需要帮助。
请参考我的数据库语言设置
使用json_encode($item, JSON_UNESCAPED_UNICODE);
。它将逐字编码多字节字符。你可以在这里获得更多信息。
实际上很奇怪你的客户端不能处理转义字符。你具体用什么?
感谢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行为是非常难以捉摸的。
检查文档:http://php.net/manual/en/function.json-encode.php
有一些选项可以让你正确编码你的数据