php json_encode() 显示 null 而不是文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8143163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php json_encode() show's null instead of text
提问by eric.itzhak
I am reading from database with some text in Hebrew and trying to json_encode
it.
if i print_r
the results i get:
我正在从数据库中读取一些希伯来语文本并尝试使用json_encode
它。如果print_r
我得到的结果:
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:
而 json_encode 显示:
[{"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.
我相信这是因为我的数据库中的文本包含 ( ' ) 标记。尝试了各种stripslashes或real_escape_string的组合都没有帮助。
回答by phihag
json_encode
expects strings in the data to be encoded as UTF-8.
json_encode
期望数据中的字符串被编码为 UTF-8。
Convert them to UTF-8 if they aren't already:
如果尚未将它们转换为 UTF-8:
$results = array_map(function($r) {
$r['text'] = utf8_encode($r['text']);
return $r;
}, $results);
echo json_encode($results);
回答by marquito
Best and quickest solution I found was in the PHP Reference itself, by Sam Barnum
我找到的最好和最快的解决方案是在 PHP 参考本身中,作者是 Sam Barnum
$encodedArray = array_map(utf8_encode, $rawArray);
回答by ouzza
$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")
);
回答by Metin Erbek
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));
此递归函数会将空值更改为 '' 空字符串。当调用 json_encode($your_array) 到 json_encode(change_null($your_array));
回答by Muhammad Tanweer
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 查询设置 CHARSET。如果要为所有查询设置相同的字符集,只需在配置或数据库连接文件中添加以下内容。
mysql_query('SET CHARACTER SET utf8');
If you just want it on specific queries, then just use this right before executing your queries
如果您只想在特定查询上使用它,那么在执行查询之前就使用它