PHP。 Json包含西里尔文数据的NULL值

时间:2014-09-16 09:27:25

标签: php json null cyrillic

我正在尝试以JSON格式获取数据。在数据库中,'employee'表包含西里尔文的数据

<?php
$mysqli = new mysqli("localhost","user","password","db");
    $myArray = array();
    if ($result = $mysqli->query("SELECT * FROM employee")) {
        $tempArray = array();
        while($row = $result->fetch_object()) {
                $tempArray = $row;
                array_push($myArray, $tempArray);
            }
        echo json_encode($myArray);
    }

    $result->close();
    $mysqli->close();
?>

结果包含NULL而不是西里尔文中的值。

[
{
id: "1",
lastname: null,
firstname: null,
middle: null,
occupation: null,
dob: "1991-01-01",
mobile: "+99999 9999999",
home: "+77777 7777777",
email: "testmail@mail.ru"
}
]

myArray的输出:

  

一个:2:{I 0,O:8: “stdClass的”:9:{S:2: “ID”,S:1: “1”; S:8: “姓氏”; S:7 : “Азизов”; S:9: “姓名”; S:6: “Азиз”; S:6: “中间”; S:14: “Азизович”; S:10: “职业”; S:19:” Android的   разработчик “; S:3:” DOB “; S:10:” 1991-01-01 “; S:6:” 移动 “; S:13:” + 99999999999 “; S:4:” 家“; S: 13: “+ 777777777777”; S:5: “电子邮件”; S:22: “testmail@mail.ru”;}}

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我刚刚添加了$mysqli->set_charset("utf8");这行代码将数据编码为UTF-8格式。为什么不工作?因为json_encode需要UTF-8中的数据

<?php
$mysqli = new mysqli("localhost","user","password","db");
$mysqli->set_charset("utf8");
    $myArray = array();
    if ($result = $mysqli->query("SELECT * FROM employee")) {
        $tempArray = array();
        while($row = $result->fetch_object()) {
                $tempArray = $row;
                array_push($myArray, $tempArray);
            }

        echo json_encode($myArray);
        //echo serialize($myArray);
    }

    $result->close();
    $mysqli->close();
?>