【问题标题】:UTF-8 characters are not displayed correctly in JSON formatUTF-8 字符无法以 JSON 格式正确显示
【发布时间】:2018-04-24 07:32:56
【问题描述】:

我使用 json 从我的数据库中回显变量。然而 ë 显示为■。

为了纠正这个问题,我这样做了:

没有运气。任何想法如何解决。

编辑:

if (isset($_GET['term'])){
$return_arr = array();

try {
    $conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare('SELECT School FROM Schools WHERE School LIKE :term');
    $stmt->execute(array('term' => '%'.$_GET['term'].'%'));

    while($row = $stmt->fetch()) {
        $return_arr[] =  $row['School'];
    }

} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}


/* Toss back results as json encoded array. */

echo mb_detect_encoding($return_arr, 'auto');

}

【问题讨论】:

  • 您考虑过JSON_UNESCAPED_UNICODE 标志吗?见php.net/manual/en/function.json-encode.php
  • 我试过了,结果还是一样
  • echo mb_detect_encoding('■', 'auto');返回它已经是 UTF-8。 JSON_UNESCAPED_UNICODE 不会帮助您,因为 "\xc3\xa9" 是 é 的未转义 unicode。我怀疑问题出在您的数据库字符集中
  • 它不是数据库。我已经通过编写 test.php 来回显没有 json 的变量来进行测试。如果没有 JSON,它会正确显示。
  • 它仍然可能是数据库。如果从数据库中获取变量,然后运行 ​​echo mb_detect_encoding($variable, 'auto'),结果是什么

标签: php json pdo utf-8 character-encoding


【解决方案1】:

1) 在json_encode 中使用JSON_UNESCAPED_UNICODE

2) 确保数据存储、数据访问、 以 UTF-8 字符集 (UTF-8 all the way through) 输出和输入。

【讨论】:

  • 它不是数据库。我已经通过编写 test.php 来回显没有 json 的变量来进行测试。如果没有 JSON,它会正确显示。
【解决方案2】:

首先,看看你的表格是否真的是utf8 编码的。它应该看起来像这样:

CREATE TABLE `Schools` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `School` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

然后像这样连接到您的数据库:

$dsn = 'mysql:dbname=test;host=127.0.0.1;port=3306;charset=utf8';
$user = 'root';
$password = 'password';
$conn = new PDO($dsn, $user, $password, [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"]);

最后使用JSON_UNESCAPED_UNICODE:

echo json_encode($row, JSON_UNESCAPED_UNICODE);

这应该可以解决问题。

更新

这适用于我上面提供的表格中的 PHP7.1:

if (isset($_GET['term'])) {
    $return_arr = array();

    try {
        $conn = new PDO("mysql:host=127.0.0.1;port=8101;dbname=test;charset=utf8", $user, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $conn->prepare('SELECT School FROM Schools WHERE School LIKE :term');
        $stmt->execute(array('term' => '%'.$_GET['term'].'%'));

        $return_arr = [];
        while($row = $stmt->fetch()) {
            $return_arr[] =  $row['School'];
        }

    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }


    /* Toss back results as json encoded array. */

    echo json_encode($return_arr, JSON_UNESCAPED_UNICODE);

}

【讨论】:

  • 它不是数据库。我已经通过编写 test.php 来回显没有 json 的变量来进行测试。如果没有 JSON,它会正确显示。
  • @CharlesTester 您在连接到数据库时仍然需要设置字符集,没有字符集将无法正常工作。请参阅我的更新答案。
猜你喜欢
  • 1970-01-01
  • 2011-08-09
  • 2020-05-15
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多