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
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.
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.
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.
Are there any other ways to interact with the POST-ed JSON object that I'm missing? Thanks!
Send JSON data via POST with PHP cURLInitiate new cURL resource using curl_init(). Setup data in PHP array and encode into a JSON string using json_encode(). Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option. Set the Content-Type of request to application/json using the CURLOPT_HTTPHEADER option.
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
PHP File explained:Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as JSON using the json_encode() function.
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.
Hope this helps someone else!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With