2011-12-02 97 views
1

我编码用户entred与json_encode testarea内容这里是它在MySQL如何storred(有 “AAA” 之后返回到线)json_decode(json_encode(索引数组))给出了NULL

{"content":"aaa 
bbb"} 

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

什么wrrong? 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 
    } 
+2

我们可以看到如何编码/解码这阵? – Tom

+0

它可能是utf8。几乎相同的讨论检查http://stackoverflow.com/questions/689185/json-decode-returns-null-php。 – Kerhong

回答

4

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

+0

外观极好,所以我河畔从MySQL获得内容也应该被一些PHP温控功能逃过一劫。谢谢 – Hassan