duanli9930 2016-10-18 12:48
浏览 159
已采纳

PHP获取JSON POST数据

I've setup a Webhook to get notifications posted to a PHP page on my server. The notification request to my server is like this:

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

I've tried using the following to convert the JSON data to a string that I can work with, but I'm getting nothing so far:

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

Everything I've read indicates this should work - I tested the following and this is actually working:

$webhookContent = "";

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

I'm trying to understand why file_get_contents('php://input'); doesn't work when everything I've read indicates that's the function I should be using, and why fopen('php://input' , 'rb'); works instead?

If I do var_dump($inputJSON) I get:

    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) returns NULL

  • 写回答

1条回答 默认 最新

  • duanchi0883649 2016-11-07 09:16
    关注

    The following is working for me now:

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

    I think my issue was using:

    $input= json_decode( $inputJSON, TRUE ); 
    

    instead of just:

    $input= json_decode( $inputJSON ); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改