Parsing JSON POST Request Bodies in PHP without PECL
Retrieving and parsing JSON request bodies in PHP scripts can be challenging, particularly when dealing with POST requests. This article addresses the issue of accessing and interacting with POST-ed JSON objects in PHP, without the use of HTTP request body function calls like http_get_request_body().
Solution
To effectively parse JSON POST request bodies in PHP without PECL, a simple and straightforward approach is to utilize the following two steps:
The second parameter in json_decode (TRUE) ensures that the JSON object is returned as an array, facilitating easy access to its properties and values.
Sample Code
Here's a sample PHP script that demonstrates the above approach:
<?php // Read the JSON request body $inputJSON = file_get_contents('php://input'); // Convert the JSON string to an array $input = json_decode($inputJSON, TRUE); // Access and interact with the JSON object // (e.g., print the value of a property) echo $input['name']; ?>
The above is the detailed content of How to Parse JSON POST Request Bodies in PHP without PECL?. For more information, please follow other related articles on the PHP Chinese website!