简体   繁体   English

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

[英]UTF-8 characters are not displayed correctly in JSON format

I use json to echo variables from my database. 我使用json从数据库中回显变量。 However ë display as ■. 但是ë显示为■。

In an attempt to correct this I have done this: 为了解决这个问题,我这样做:

With no luck. 没有运气。 Any ideas how to fix. 任何想法如何解决。

EDIT: 编辑:

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');

}

First, take a look if your table is actually utf8 encoded. 首先,看看您的表是否实际上是utf8编码的。 It should look something like this: 它看起来应该像这样:

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;

Then connect to your database like this: 然后像这样连接到数据库:

$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'"]);

Finally use JSON_UNESCAPED_UNICODE : 最后使用JSON_UNESCAPED_UNICODE

echo json_encode($row, JSON_UNESCAPED_UNICODE);

This should do the trick. 这应该可以解决问题。

UPDATE UPDATE

This worked on PHP7.1 on the table I provided above: 我在上面提供的表上在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) Use JSON_UNESCAPED_UNICODE in json_encode . 1)在json_encode使用JSON_UNESCAPED_UNICODE

2) Make sure that data storage, data access, output and input in UTF-8 charset ( UTF-8 all the way through ). 2)确保数据存储,数据访问,输出和输入均采用UTF-8字符集( 一直到UTF-8 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM