2011-12-02 45 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