php json_encode() show's null instead of text

eric.itzhak picture eric.itzhak · Nov 15, 2011 · Viewed 24.3k times · Source

I am reading from database with some text in Hebrew and trying to json_encode it. if i print_r the results i get:

Array
(
    [0] => Array
        (
            [value] => 88
            [text] => כיתה א'
            [parent_id] => 1
            [level] => 1
        )

    [1] => Array
        (
            [value] => 89
            [text] => כיתה ב'
            [parent_id] => 1
            [level] => 1
        )

    [2] => Array
        (
            [value] => 91
            [text] => כיתה ג'
            [parent_id] => 1
            [level] => 1
        )

)

while the json_encode shows:

[{"value":"88","text":null,"parent_id":"1","level":"1"},{"value":"89","text":null,"parent_id":"1","level":"1"},{"value":"91","text":null,"parent_id":"1","level":"1"}]

i belive it's because my text from the database contains a ( ' ) mark. tried various combination of stripslashes or real_escape_string none have helped.

Answer

phihag picture phihag · Nov 15, 2011

json_encode expects strings in the data to be encoded as UTF-8.

Convert them to UTF-8 if they aren't already:

$results = array_map(function($r) {
  $r['text'] = utf8_encode($r['text']);
  return $r;
}, $results);
echo json_encode($results);