php - MySQL 到 JSON : Issue with encoding of German special characters in UTF-8

标签 php mysql json encoding utf-8

我写了一个小脚本,从 MySQL 表中获取数据并将其放入 JSON 数组中。但是,字符编码存在问题,即使我在所有地方都设置了 UTF-8。这是脚本:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JSON</title>
</head>

<?php

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

$con = mysqli_connect("HOST", "USERNAME", "PASSWORD", "DATABASE");
if (!$con) {
    trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}

mysqli_set_charset($con,"utf8");

mysql_query("SET NAMES SET 'utf8'"); 
mysql_query("SET character_set_client = 'utf8'"); 
mysql_query("SET character_set_connection = 'utf8'"); 
mysql_query("SET character_set_results = 'utf8'");

$sql = "SELECT * FROM table";

$result = mysqli_query($con, $sql);

$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    $rows[]=$r;
}

print json_encode($rows);


mysqli_close($con);

?>

</html>

在输出中,我得到值“\u00e4”而不是“ä”。

一些附加信息:

  • 表在 utf8_general_ci 中(它的所有列也是如此)
  • PHP 文件是 UTF8 格式

我做错了什么? 感谢您的帮助!!

最佳答案

在我看来一切正常。您看到 \u00e4 而不是 ä 的原因是因为 JSON 序列化程序的实现。序列化程序所做的是完全有效的。

来自JSON RFC Section 2.5 Strings

Any character may be escaped. If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point. The hexadecimal letters A though F can be upper or lowercase. So, for example, a string containing only a single reverse solidus character may be represented as "\u005C".

我怀疑为什么这个序列化器会为你转义它的原因是因为 PHP doesn't natively support unicode .

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support.

关于php - MySQL 到 JSON : Issue with encoding of German special characters in UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25692949/

相关文章:

php - 如何使用 PHP 在 DOMElement 上执行 XPath 查询?

php - 如何使用 jQuery 将 div 的宽度更改为 100%?

php - 如何使用codeigniter上传数据到数据库

mysql - Shiny 的服务器 - 安排 mysql 查询而不是每次加载应用程序时运行?

javascript - 如何浏览一个javascript对象

php - Windows 10 无法将 AWS SDK for PHP v3 与 Composer 一起使用

mysql - MySQL 中 PostgreSQL 的 array_agg() 和 array_to_string

php - 从 PHP 洗牌中获取输出并将其插入到新的数据库表中

javascript - 如何在 VueJS 中动态创建输入字段

jquery - 我需要在此 jQuery 自动完成示例中更改哪些内容才能使其与我的 JSON url 一起使用?