2012-09-29 79 views
0

我有一個返回從$_POST一個JSON編碼的響應函數:PHP數據從郵政

function getdatafrompost(){ 
    $raw = '';  
    $httpContent = fopen('php://input', 'r'); 
    while ($kb = fread($httpContent, 1024)) 
     $raw .= $kb;   
    fclose($httpContent);  
    $params = array(); 
    parse_str($raw, $params); 
    if (isset($params['data'])) 
     $retdata = json_decode(stripslashes($params['data'])); 
    else 
     $retdata = json_decode(stripslashes($raw)); <====Returns Null 
    return $retdata; 
} 

讀取原始數據是:

{"recordid":"099ac8aa-0a43-11e2-860f-0016177c526f","ntsdataid":"","trkdataid":"5628af8e-08db-11e2-860f-0016177c526f","activitydate":"2012-09-29","activitytime":"10:36:21","activityname":" from S. Interrante","activitynote":"<i><font color=\"99CC00\" size=\"4\"><b><font face=\"verdana\">fgsdfgsdgsdfgsdgsdgsdfg</font>\u200b</b></font></i>"} 

問題是$retdata被返回null。這似乎在包含HTML的「activitynote」字段中。當「activitynote」不包含HTML時,數據將被正確解析。有沒有更好的方法來解析數據?我做錯了什麼嗎?

回答

0

你不應該使用stripslashes,它會影響到JSON文件來修復這個錯誤的有效性就應該更換

json_decode(stripslashes($raw)) 

隨着

json_decode($raw); 

$raw = '{"recordid":"099ac8aa-0a43-11e2-860f-0016177c526f","ntsdataid":"","trkdataid":"5628af8e-08db-11e2-860f-0016177c526f","activitydate":"2012-09-29","activitytime":"10:36:21","activityname":" from S. Interrante","activitynote":"<i><font color=\"99CC00\" size=\"4\"><b><font face=\"verdana\">fgsdfgsdgsdfgsdgsdgsdfg</font>\u200b</b></font></i>"}' ; 
var_dump(json_decode($raw)); 

輸出

object(stdClass)[1] 
    public 'recordid' => string '099ac8aa-0a43-11e2-860f-0016177c526f' (length=36) 
    public 'ntsdataid' => string '' (length=0) 
    public 'trkdataid' => string '5628af8e-08db-11e2-860f-0016177c526f' (length=36) 
    public 'activitydate' => string '2012-09-29' (length=10) 
    public 'activitytime' => string '10:36:21' (length=8) 
    public 'activityname' => string ' from S. Interrante' (length=19) 
    public 'activitynote' => string '<i><font color="99CC00" size="4"><b><font face="verdana">fgsdfgsdgsdfgsdgsdgsdfg</font>​</b></font></i>' (length=105) 
+0

謝謝你的幫助巴巴! – user1532602

+0

不客氣 – Baba