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 ); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝