从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对象发布到我的脚本,我想用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 $中的第二个参数c $ c>将对象作为数组返回。
where the second parameter in json_decode
returned the object as an array.
希望这有助于其他人!
这篇关于从PHP中的JSON POST读取HTTP请求正文的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!