Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php json_encode() show's null instead of text

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.

like image 722
eric.itzhak Avatar asked Nov 15 '11 21:11

eric.itzhak


3 Answers

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);
like image 111
phihag Avatar answered Oct 06 '22 19:10

phihag


Best and quickest solution I found was in the PHP Reference itself, by Sam Barnum

$encodedArray = array_map(utf8_encode, $rawArray);
like image 33
marquito Avatar answered Oct 06 '22 17:10

marquito


$dbh = new PDO('mysql:host=localhost;dbname=test', 
                $user, 
                $pass
              ); 

$dbh->exec("SET CHARACTER SET utf8");

or

$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", 
                $dbuser, 
                $dbpass, 
                array( PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
              );
like image 2
ouzza Avatar answered Oct 06 '22 19:10

ouzza