【问题标题】:PHP cannot extract JSON from HTTP POSTPHP 无法从 HTTP POST 中提取 JSON
【发布时间】:2021-03-09 02:37:27
【问题描述】:

我有一个接收此信息的 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这两个变量写入数据库;但是,这两个变量都是空的

我错过了什么?

【问题讨论】:

  • file_get_contents('php://input') 的转储是什么?
  • 基于您的 json,例如路径userId 将是:echo $data['body']['registrations'][0]['userId'];
  • 不应该是$data['body']['registrations'][0]['userId'];$data['body']['registrations'][0]['userAccessToken'];吗? (正文索引)

标签: php json post file-io file-get-contents


【解决方案1】:

您的变量中缺少一些键。此外,我建议添加异常处理程序以防 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'];

【讨论】:

  • 感谢您的建议。至少json_decode通过了try-catch,但是变量还是空的。
【解决方案2】:

这是解决方案。

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

我猜是因为 'php://input' 已经返回了请求正文。

感谢您的 cmets 和帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    相关资源
    最近更新 更多