PHP 获取 JSON POST 数据

标签 php json http

我已经设置了一个 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

最佳答案

以下内容现在对我有用:

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

我认为我的问题是使用:
$input= json_decode( $inputJSON, TRUE ); 

而不仅仅是:
$input= json_decode( $inputJSON ); 

关于PHP 获取 JSON POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40108736/

相关文章:

javascript - 在删除之前使用 JavaScript 进行提示不起作用

php - Laravel 5.4 测试路由受 $request->ajax() 保护,如何发起测试 ajax 请求?

ios - 检索 JSON 对象 Swift 2

html - 如何自动下载可通过 html 表单获取的数据?我应该学什么?

http - URL 路径和查询字符串和片段的好名称?

php - 带有静态连接字符串变量的奇怪解析错误

php - symfony2 中可选的多个 oneToMany 关系

json - Swift 3 - 返回 null 的 SwiftyJSON 字符串

javascript - 当 JSON 中嵌入了脚本标记时,JSON 会抛出错误

http - 负数组大小异常