无法json_encode对象数组

时间:2014-08-24 12:33:41

标签: php json

我有一个PHP类Country,我从数据库函数调用返回为对象数组。我可以做var_dump($ countries)并查看对象,但等效的json_encode($ countries)不返回任何内容。

class Country implements JsonSerializable{
    private  $id;
    private  $name;

    public function jsonSerialize() {
        return (object) get_object_vars($this);
    }

    //Getters and setters
}

//Happening in a function
try {
    $sql = "SELECT * FROM country";
    $stmt = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_NAMED, PDO::FETCH_ORI_NEXT)) {
        $country = new Country();
            $country->setId($row["id"]);
            $country->setName($row["name"]);
        $countries[] = $country;
    }
    $stmt = null;
} catch (PDOException $e) {
    //Other stuff
}
error_log(count($countries));          //Returns the actual count (23)  
error_log(json_encode($countries[0])); //Returns the JSON Encoded Country Object {"id":"1","name":"The Name"}
error_log(json_encode($countries));    //Returns NOTHING

error_log(var_dump($countries));       //Returns the dumped array:   array(230) { [0]=> object(Country)#5 (8) { ["id":"Country":private]=> string(1) "1" ["name":"Country":private]=> string(7) "The Name"} [1]=> object(Country)#6 (8) { .............}}

我的问题是我需要返回JSON编码的国家/地区列表,但json_encode($ countries)会返回NOTHING。但是,其他日志按预期返回。请朋友们问题是什么?

2 个答案:

答案 0 :(得分:0)

我想承认,如果没有@MichaelBerkowski和@ialarmedalien的建议,我不会得到这个答案。

首先,问题源于导入MySQL的记录源。我真的不知道在源记录上使用了什么字符编码,但我确信它不是“UTF-8字符”。

根据@MichaelBerkowski建议在尝试编码从数据库返回的对象列表后记录了json_last_error()和json_last_error_msg():

error_log(json_encode($countries)); //Return NOTHING
error_log(json_last_error()); //Returns 5
error_log(json_last_error_msg()); Return "Malformed UTF-8 characters, possibly incorrectly encoded" which explains what the problem is

调试:

while ($row = $stmt->fetch(PDO::FETCH_NAMED, PDO::FETCH_ORI_NEXT)) {
    $country = new Country();
        $country->setId($row["id"]);
        $country->setName($row["name"]);
        error_log($row['id']."  ::: ".json_encode($country));
    $countries[] = $country;
}

[Sun Aug 24 13:52:28.357533 2014] [:error] [pid 11319] [client 127.0.0.1:41112] 10: {"id":"10","name":"The Name"}
[Sun Aug 24 13:52:28.357662 2014] [:error] [pid 11319] [client 127.0.0.1:41112] 11: 
[Sun Aug 24 13:52:28.357773 2014] [:error] [pid 11319] [client 127.0.0.1:41112] 12: {"id":"12","name":"The Name"}

最后,只有id值的行是导致问题的行,因此,我使用id值手动检查数据库列并替换áóååíúá字符串来修复问题。

答案 1 :(得分:0)

你的字符串部分可能只有一个qoutes,你需要首先使用str_replace来逃避它

$newstr =str_replace('\'', '\\\'', $myString);

执行json_encode后

json_encode($newstring, true);

希望它能解决问题。