PHP获取JSON POST数据

6
我已经设置了一个Webhook,可以将通知发布到我的服务器上的PHP页面。发送到我的服务器的通知请求如下:
POST /message/receive HTTP/1.1
Host: http://www.yoururl.com/zipwhip/api/receive
Content-Length: 581
Content-Type: application/json; charset=UTF-8

{ "body":"Thanks for texting, this is an auto reply!",
  "bodySize":42,
  "visible":true,
  "hasAttachment":false,
  "dateRead":null,
  "bcc":null,
  "finalDestination":"4257772300",
  "messageType":"MO",
  "deleted":false,
"statusCode":4,
"id":634151298329219072, "scheduledDate":null, "fingerprint":"132131532", "messageTransport":9, "contactId":3382213402, "address":"ptn:/4257772222",
"read" "dateCreated":"2015-08-19T16:53:45-07:00", "dateDeleted":null,
  "dateDelivered":null,
  "cc":null,
  "finalSource":"4257772222",
} "dev

我尝试使用以下方法将JSON数据转换为可处理的字符串,但迄今为止什么都没有:

$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE ); 

根据我所读的,这应该可以实现 - 我测试了以下内容,确实有效:

$webhookContent = "";

    $webhook = fopen('php://input' , 'rb');
    while (!feof($webhook)) {
        $webhookContent .= fread($webhook, 4096);
    }
    fclose($webhook);

我在努力理解为什么使用file_get_contents('php://input')时无法正常工作,而我读到的所有内容都表明这是我应该使用的函数,以及为什么使用fopen('php://input', 'rb')却可以正常工作?

如果我执行var_dump($inputJSON),我会得到:

    string(527) "{ "body":"Thanks for texting, this is an auto reply!",
  "bodySize":42,
  "visible":true,
  "hasAttachment":false,
  "dateRead":null,
  "bcc":null,
  "finalDestination":"4257772300",
  "messageType":"MO",
  "deleted":false,
"statusCode":4,
"id":634151298329219072, "scheduledDate":null, "fingerprint":"132131532", "messageTransport":9, "contactId":3382213402, "address":"ptn:/4257772222",
"read" "dateCreated":"2015-08-19T16:53:45-07:00", "dateDeleted":null,
  "dateDelivered":null,
  "cc":null,
  "finalSource":"4257772222",
}"

var_dump($input)返回NULL


那么哪里出了问题?var_dump($inputJSON)输出了什么? - jeroen
2
您的 JSON 看起来对我来说不是有效的。 - simon
@jeroen 我已经编辑了问题,包括 var_dump($inputJSON) 的结果。 - user982124
那不是有效的 JSON。你是如何创建它的? - jeroen
看起来这是序列化数据而不是JSON数据,尝试使用PHP的serialize()和unserialize()函数而不是json_****()函数... - himeshc_IB
@jeroen JSON数据来自外部网络服务。我已经尝试使用本地cURL复制他们的请求,并遇到了相同的问题。看起来是内容长度(在var_dump($inputJSON)值的开头的string(527))。看起来file_get_contents('php://input');也返回了内容长度?这正常吗? - user982124
1个回答

13
以下方法现在对我可行:
$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON ); 

我认为我的问题在于使用了:

$input= json_decode( $inputJSON, TRUE ); 

仅仅是:

$input= json_decode( $inputJSON ); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接