来自Post的PHP数据

时间:2012-09-29 14:55:21

标签: php html http-post

我有一个函数从$_POST返回json编码的响应:

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。这似乎位于“activitynote”字段中,其中包含HTML。当“activitynote”不包含HTML时,将正确解析数据。有没有更好的方法来解析数据?我做错了什么吗?

1 个答案:

答案 0 :(得分: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)