php - 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
数据库;但是,这两个变量都是空的
我错过了什么?
解决方案
您的变量中缺少一些键。此外,我建议添加异常处理程序以防 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'];
推荐阅读
- c++ - 我可以使用 std::vector::insert 向自身插入一个向量吗?
- r - 即使我的变量相同,为什么我的行不会合并?
- iso-7816-4 - 如果 ISO 7816 的 SE 模板中存在多个 CRT,会发生什么情况?
- javascript - 用于根据受访者选择的答案在 Google 表单中选择部分的 Google App 脚本
- ldap - 是否可以在 sssd 的 ldap 主目录中进行子字符串替换
- blockchain - 从使用 etherscan api 获取的交易列表中获取拥有的 NFT
- reactjs - 400 BAD 请求 HTTP 错误代码如何修复
- c++ - CRC8 Slice-by-4 算法
- javascript - 如何以不同的时间间隔和不同的参数顺序调用异步函数
- python - TypeError: load() 缺少 1 个必需的位置参数:'Loader'