Why would json_encode return an empty string

Well after 2 hours of digging (cf Edits)

I found out following :

  • In my case it's a encoding problem
  • mb_detect_encoding returns probably a faulty response, some strings were probably not UTF-8
  • using utf8_encode() on those string solved my problem, but see note below

Here is a recursive function that can force convert to UTF-8 all the strings contained in an array:

function utf8ize($d) {
    if (is_array($d)) {
        foreach ($d as $k => $v) {
            $d[$k] = utf8ize($v);
        }
    } else if (is_string ($d)) {
        return utf8_encode($d);
    }
    return $d;
}

Use it simply like this:

echo json_encode(utf8ize($data));

Note: utf8_encode() encodes ISO-8859-1 string to UTF-8 as per the docs so if you are unsure of the input encoding iconv() or mb_convert_encoding() may be better options as noted in comments and other solutions.


Matthieu Riegler presented really good solution however I had to slightly modify it to handle objects too:

function utf8ize($d) {
    if (is_array($d)) 
        foreach ($d as $k => $v) 
            $d[$k] = utf8ize($v);

     else if(is_object($d))
        foreach ($d as $k => $v) 
            $d->$k = utf8ize($v);

     else 
        return utf8_encode($d);

    return $d;
}

One more note: json_last_error() may be helpful in debugging json_encode()/json_encode() functions.


For me, the answer to this problem was setting charset=utf8 in my PDO connection.

$dbo = new PDO('mysql:host=localhost;dbname=yourdb;charset=utf8', $username, $password);

Tags:

Php

Json