【问题标题】:json_decode(json_encode(an indexed array)) gives NULLjson_decode(json_encode(一个索引数组)) 给出 NULL
【发布时间】:2011-12-02 08:44:11
【问题描述】:

我使用 json_encode 对用户输入的 testarea 内容进行编码 这是它在mysql中的存储方式(“aaa”之后有一个返回行)

{"content":"aaa
bbb"}

现在,当我从数据库中获取内容并尝试使用 json_decode 对其进行解码时,我得到的是 NULL,而不是预期的结果。

怎么了? PHP 中的错误?

编辑 1:更多细节

$data =array('content'=>$textareaText);
$addres_insert = "INSERT INTO `rtable` (`data`) VALUES ('".json_encode($data)."');";
$rows = mysql_query($addres_insert);

然后去获取内容

$query = "SELECT * FROM  `rtable` WHERE id =  '".$id."'";
        $rows = mysql_query($query);
    if ( $rows ){
        $row = mysql_fetch_array($rows);
        $res['data'] = json_decode($row['data']);//i tryed substr($row['data'],3) but didn't work
    }

【问题讨论】:

标签: php mysql json


【解决方案1】:

JavaScript 和 JSON 不允许在字符串中包含换行符。你需要逃离他们。

json_encode() 应该会自动为您转义它们。

这是我在 PHP 交互式 shell 上提供的 JSON 代码的输出:

php > $json = '{"content":"aaa
php ' bbb"}';
php > var_dump(json_decode($json, true));
NULL

正如你所看到的,当我转义你的线路时,它工作得很好:

php > $json = '{"content":"aaa\n bbb"}';
php > var_dump(json_decode($json, true));
array(1) {
  ["content"]=>
  string(8) "aaa
 bbb"
}

这也在与类似问题相关的上一个问题中进一步讨论:Problem when retrieving text in JSON format containing line breaks with jQuery

【讨论】:

  • excelent ,所以对于我从 mysql 获得的内容也应该使用一些 php 功能进行转义。谢谢
猜你喜欢
  • 2018-01-30
  • 1970-01-01
  • 2018-11-05
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2017-09-09
  • 2013-12-20
  • 2015-08-21
相关资源
最近更新 更多