首页 > 解决方案 > PHP 无法从 HTTP POST 中提取 JSON

问题描述

我有一个接收此信息的 API 端点:

{
  "method": "POST",
  "path": "/",
  "query": {},
  "headers": {
    "x-forwarded-for": "xxx.xxx.xxx.xx",
    "x-forwarded-proto": "https",
    "x-forwarded-port": "443",
    "host": "xxx",
    "x-amzn-trace-id": "xxx",
    "content-length": "128",
    "accept": "text/plain, application/json, application/*+json, */*",
    "user-agent": "xxx",
    "content-type": "application/json;charset=UTF-8",
    "accept-encoding": "gzip,deflate"
  },
  "bodyRaw": "{\"registrations\":[{\"userId\":\"xxx\",\"userAccessToken\":\"550a3a10-a3be-4784-89e2-42e7c8865883\"}]}",
  "body": {
    "registrations": [
      {
        "userId": "xxx",
        "userAccessToken": "550a3a10-a3be-4784-89e2-42e7c8865883"
      }
    ]
  }
}

我无法提取这两个参数。我在 PHP 中使用此代码:

$data = json_decode(file_get_contents('php://input'),true);
$userID = $data['registrations']['userId'];
$userToken = $data['registrations']['userAccessToken'];

$userID然后我将这两个变量写入$userToken数据库;但是,这两个变量都是空的

我错过了什么?

标签: phpjsonpostfile-iofile-get-contents

解决方案


您的变量中缺少一些键。此外,我建议添加异常处理程序以防 php://input 引发错误。你可以试试这个:

try {
    $data = json_decode( file_get_contents( 'php://input' ), TRUE, 512, JSON_THROW_ON_ERROR );
} catch ( JsonException $e ) {
    var_dump($e->getMessage());
}
$userID = $data['body']['registrations'][0]['userId'];
$userToken = $data['body']['registrations'][0]['userAccessToken'];

推荐阅读