问题
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.
回答1:
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);
回答2:
Best and quickest solution I found was in the PHP Reference itself, by Sam Barnum
$encodedArray = array_map(utf8_encode, $rawArray);
回答3:
$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")
);
回答4:
Try json_encode($string, JSON_UNESCAPED_UNICODE);
(only for PHP v5.4.0+ - see docs).
回答5:
function change_null($d)
{
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = change_null($v);
}
} else if(is_null($d))
{
return '';
}
return $d;
}
This recursive function will change null values to '' empty string. When calling json_encode($your_array) to json_encode(change_null($your_array));
回答6:
One of the easiest way is to SET the CHARSET for MySQL query. If you want to set the same charset for all your queries, then just add the following in your configuration or database connection file.
mysql_query('SET CHARACTER SET utf8');
If you just want it on specific queries, then just use this right before executing your queries
来源:https://stackoverflow.com/questions/8143163/php-json-encode-shows-null-instead-of-text