PHP无法从HTTP POST提取JSON
我有一个接收以下信息的API端点:PHP无法从HTTP POST提取JSON,php,json,post,file-io,file-get-contents,Php,Json,Post,File Io,File Get Contents,我有一个接收以下信息的API端点: { "method": "POST", "path": "/", "query": {}, "headers": { "x-forwarded-for": "xxx.xxx.xxx.xx", "x-forwarded-proto": "htt
{
"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'];
这是解决办法
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'已返回请求正文
感谢您的评论和帮助文件的转储内容是什么php://input“)?根据您的json,例如,
userId
的路径是:echo$data['body']['registrations'][0]['userId']
不应该是$data['body']['registrations'][0]['userId']
和$data['body']['registrations'][0]['userAccessToken']代码>?(身体指数)谢谢你的建议。至少json_解码通过了try-catch,但是变量仍然是空的。