从 PHP 中的 JSON POST 读取 HTTP 请求正文的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7047870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Issue reading HTTP request body from a JSON POST in PHP
提问by Hartley Brody
I'm writing a script that is registered as an endpoint for a webhook. I know that it's successfully registered because I'm writing the header of every request to my server logs. Here's a sample:
我正在编写一个注册为 webhook 端点的脚本。我知道它已成功注册,因为我正在将每个请求的标头写入服务器日志。这是一个示例:
Content-Type: text/xml; charset=UTF-8
User-Agent: Jakarta Commons-HttpClient/3.1
Host: =={obfuscated}==
Content-Length: 1918
The API that I've registered with is POST-ing a JSON object to my script, and I'd like to parse that object using PHP. As you can see from the request header, there's a nice big fat JSON object waiting to be parsed. It seems straightforward, but it hasn't been.
我注册的 API 是将 JSON 对象 POST 到我的脚本中,我想使用 PHP 解析该对象。正如您从请求标头中看到的,有一个很大的 JSON 对象等待解析。看起来很简单,但事实并非如此。
At first I tried using $_POST['json']
or just $_POST
but since the data isn't in an array, I wasn't really sure how to access it like that.
起初我尝试使用$_POST['json']
or just$_POST
但由于数据不在数组中,我不确定如何像那样访问它。
I've tried using file_get_contents('php://input')
and fopen('php://input', 'r')
with and without json_decode()
but no luck. I can't use http_get_request_body()
since the server I'm on doesn't have PECL and that's out of my control.
我试过使用file_get_contents('php://input')
和fopen('php://input', 'r')
不使用,json_decode()
但没有运气。我无法使用,http_get_request_body()
因为我所在的服务器没有 PECL,这是我无法控制的。
Are there any other ways to interact with the POST-ed JSON object that I'm missing? Thanks!
还有其他方法可以与我缺少的 POST-ed JSON 对象进行交互吗?谢谢!
回答by Hartley Brody
Thanks to others for the input. It turns out that I just needed
感谢其他人的投入。原来我只需要
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
where the second parameter in json_decode
returned the object as an array.
其中第二个参数以json_decode
数组形式返回对象。
Hope this helps someone else!
希望这对其他人有帮助!
回答by Exequiel Aguirre
Even when the following works.
即使以下有效。
$inputJSON = file_get_contents('php://input');
If you want to continue using $_POST send the data as FormData
如果您想继续使用 $_POST 将数据作为 FormData 发送
var fd = new FormData();
fd.append('key', 'value');
return axios.post('url', fd)