Q . Unable to json_encode array of objects in PHP

Mike Tyson. asked, Oct 18 ' 2017

I have a PHP class Country which I return as array of objects from a database function call. I can do var_dump($countries) and see the objects but the equivalent json_encode($countries) returns nothing.

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));
    while ($row = $stmt->fetch(PDO::FETCH_NAMED, PDO::FETCH_ORI_NEXT)) {
        $country = new Country();
        $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) { .............}}

My problem is I need to return JSON Encoded list of countries but json_encode($countries) return NOTHING. However, others logs returns as expected. Please friends what could be the issue?

  • PHP
  • error
  • json_encode

1 Answers

I want to acknowledge the fact I wouldn't have had this answer without @MichaelBerkowski and @ialarmedalien advice.

Firstly, the problem originated from the source of the record which was imported into MySQL. I don't really know what character encoding that was used on the source record but I am sure it is not "UTF-8 characters".

According @MichaelBerkowski advice logged json_last_error() and json_last_error_msg() after attempting to encode the list of objects returned from the database:

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();
        error_log($row['id']."  ::: ".json_encode($country));
    $countries[] = $country;

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

Finally the lines with only the id value are the lines that are causing the problem hence, I used the id value to manually check the database columns and replace strings like éáóüåíúá which fixed the problem.

Leave a Ansewer