php json_encode() 显示 null 而不是文本

2021-12-22 00:00:00 json text php hebrew

我正在从数据库中读取一些希伯来语文本并尝试 json_encode 它.如果我 print_r 我得到的结果:

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
        )

)

虽然 json_encode 显示:

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"}]

我相信这是因为我的数据库中的文本包含 ( ' ) 标记.尝试了各种stripslashes或real_escape_string的组合都没有帮助.

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.

推荐答案

json_encode期望数据中的字符串被编码为 UTF-8.

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

如果尚未将它们转换为 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);

相关文章