【问题标题】:Array to json with json_encode and back to text使用 json_encode 将数组转换为 json 并返回到文本
【发布时间】:2011-11-11 07:13:37
【问题描述】:

我从 mysql 数据库中检索数据。我想将这些数据作为 json 提供:

<?php
    $data = array();

    foreach($this->dataFromDb as $value){
        $data[] = $value;
    }

    $json = json_encode($data);

    echo $json;
?>

不幸的是,这会在 json 中产生 null 值,因为例如$value['title'] 可能包含非 utf-8 字符,例如 €。为了解决这个问题,我改变了这一行。

$data[] = array_map(utf8_encode, $value);

但现在我在 json 输出中有 \u00\u0080 这样的字符串。我如何获得我的普通文本,就像它从 json 存储在 db 中一样?当我尝试时

print_r(json_decode($json));

我又得到了像für 599,95€ 这样的奇怪字符。

有什么想法吗?

【问题讨论】:

    标签: php json


    【解决方案1】:

    您还必须utf8_decode() 数据:

    <?php
    
        $data = array();
        $arr[] = 'a';
        $arr[] = "\x80";
    
        print_r($arr);
    
        $data[] = array_map(utf8_encode, $arr);
    
        $json = json_encode($data);
    
        $decoded_json =  json_decode($json);
    
        print_r($decoded_json);
    
        $decoded_data[] = array_map(utf8_decode, $decoded_json[0] );
        print_r($decoded_data);
    
    ?>
    

    【讨论】:

      【解决方案2】:

      使用 iconv 在字符集之间进行转换。

      iconv("UTF-8", "CP1252", $data)
      

      【讨论】:

        【解决方案3】:

        每次连接到数据库时使用 utf-8 字符集。

        【讨论】:

          猜你喜欢
          • 2014-08-31
          • 2014-10-26
          • 2020-07-16
          • 1970-01-01
          • 2010-12-18
          相关资源
          最近更新 更多