Home >Backend Development >PHP Tutorial >How Can I Read JSON POST Data in My PHP Web Service?
Struggling to read JSON data in a PHP web service?
You have a web service that works perfectly with simple form data. However, when you need to send POST data with a content-type of application/json, your web service fails to return any values. You suspect it's related to how you're handling the POST values.
The issue lies in the way you're accessing the POST data. For JSON POST requests, you need to use a different method than the standard $_POST variable.
To read JSON data from the POST request, use the following code:
$inputJSON = file_get_contents('php://input'); $input = json_decode($inputJSON, TRUE); // Convert JSON into an array // Use the $input array to access your JSON data
In your CURL request, you're using CURLOPT_POSTFIELDS to encode your parameters as application/x-www-form-urlencoded. However, for a JSON POST request, you need to provide JSON-formatted data.
Change your CURL code to the following:
$data_string = json_encode($data); $curl = curl_init('http://webservice.local/'); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string) ));
Ensure there's only one call to header('Content-type: application/json'); in your web service page. If there are multiple calls, it can interfere with the JSON response.
The above is the detailed content of How Can I Read JSON POST Data in My PHP Web Service?. For more information, please follow other related articles on the PHP Chinese website!