从 PHP 中的 JSON POST 读取 HTTP 请求正文的问题 [英] Issue reading HTTP request body from a JSON POST in PHP
问题描述
我正在编写一个注册为 webhook 端点的脚本.我知道它已成功注册,因为我正在将每个请求的标头写入服务器日志.这是一个示例:
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:
Content-Type: text/xml; charset=UTF-8
User-Agent: Jakarta Commons-HttpClient/3.1
Host: =={obfuscated}==
Content-Length: 1918
我注册的 API 是将 JSON 对象 POST 到我的脚本中,我想使用 PHP 解析该对象.正如您从请求标头中看到的,有一个很大的 JSON 对象等待解析.看起来很简单,但事实并非如此.
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.
起初我尝试使用 $_POST['json']
或仅使用 $_POST
但由于数据不在数组中,我不确定如何像那样访问它.
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.
我试过使用 file_get_contents('php://input')
和 fopen('php://input', 'r')
有和没有json_decode()
但没有运气.我无法使用 http_get_request_body()
,因为我所在的服务器没有 PECL,这是我无法控制的.
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.
是否还有其他方法可以与我缺少的 POST-ed JSON 对象进行交互?谢谢!
Are there any other ways to interact with the POST-ed JSON object that I'm missing? Thanks!
推荐答案
感谢其他人的投入.原来我只需要
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
json_decode
中的第二个参数以数组形式返回对象.
where the second parameter in json_decode
returned the object as an array.
希望这对其他人有帮助!
Hope this helps someone else!
这篇关于从 PHP 中的 JSON POST 读取 HTTP 请求正文的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!