UTF-8字符无法以JSON格式正确显示

时间:2017-11-11 01:38:30

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

我使用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');

}

2 个答案:

答案 0 :(得分:1)

首先,看看您的表格实际上是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);

}

答案 1 :(得分:0)

1)在JSON_UNESCAPED_UNICODE中使用json_encode

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