我正在从数据库中选择一些数据并将它们编码为json,但我遇到了类似捷克标志的问题
á,í,ř,č,ž…
我的文件是utf-8编码,我的数据库也是utf-8编码,我也设置了头文件到utf-8编码.我还应该做什么?
我的代码:
header('Content-Type: text/html; charset=utf-8');
while($tmprow = MysqLi_fetch_array($result)) {
$row['user'] = mb_convert_encoding($tmprow['user'], "UTF-8", "auto");
$row['package'] = mb_convert_encoding($tmprow['package'], "UTF-8", "auto");
$row['url'] = mb_convert_encoding($tmprow['url'], "UTF-8", "auto");
$row['rating'] = mb_convert_encoding($tmprow['rating'], "UTF-8", "auto");
array_push($response, $row);
}
$json = json_encode($response, JSON_UnesCAPED_UNICODE);
if(!$json) {
echo "error";
}
和印刷的json的一部分:“包”:“zv ??? tkanalouce”
编辑:没有mb_convert_encoding()函数,打印的字符串为空,并打印“错误”.
解决方法:
json_encode($response, JSON_UnesCAPED_UNICODE);
"package":"zv???tkanalouce"
你在那里看到了问号,因为它们是由mb_convert_encoding引入的.当您使用编码检测(“auto”作为第三个参数)并且编码检测无法处理输入中的字符,将其替换为问号时,会发生这种情况.示例性代码行:
$row['url'] = mb_convert_encoding($tmprow['url'], "UTF-8", "auto");
这也意味着来自数据库的数据不是UTF-8编码的,因为mb_convert_encoding($buffer,’UTF-8′,’auto’);如果$buffer是UTF-8编码,则不会引入问号.
因此,您需要找出数据库连接中使用的字符集,因为数据库驱动程序会将字符串转换为连接的编码.
最简单的是你只需告诉每个数据库链接你要求UTF-8字符串然后只使用它们:
$MysqLi = new MysqLi("localhost", "my_user", "my_password", "test");
/* check connection */
if (MysqLi_connect_errno()) {
printf("Connect Failed: %s\n", MysqLi_connect_error());
exit();
}
/* change character set to utf8 */
if (!$MysqLi->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $MysqLi->error);
} else {
printf("Current character set: %s\n", $MysqLi->character_set_name());
}
前面的代码示例演示了如何使用MysqLi将默认客户端字符集设置为UTF-8.它已经是taken from the manual,也可以看到我们现场的材料,例如: utf 8 – PHP and MySQLi UTF8.
然后,您可以大大改善您的代码:
$response = $result->fetch_all(MysqLI_ASSOC);
$json = json_encode($response, JSON_UnesCAPED_UNICODE);
if (FALSE === $json) {
throw new LogicException(
sprintf('Not json: %d - %s', json_last_error(), json_last_error_msg())
);
}
header('Content-Type: application/json');
echo $json;