Home > Backend Development > PHP Tutorial > How to Correctly Read and Parse JSON POST Data in PHP?

How to Correctly Read and Parse JSON POST Data in PHP?

DDD
Release: 2024-12-15 20:11:12
Original
936 people have browsed it

How to Correctly Read and Parse JSON POST Data in PHP?

Reading JSON POST Data in PHP

When receiving POST data in JSON format, it's crucial to retrieve and parse it correctly in PHP. In your scenario, you encountered issues due to incorrect handling of the JSON POST data.

To resolve this, replace the usage of $_POST with other methods to read the raw input and then decode it as JSON. Here's how you can accomplish this:

Modified PHP on the Receiving Page:

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
Copy after login

This code reads the raw input as JSON and then parses it into an array that you can access with $input.

Updated CURL Code for Testing:

As mentioned in the response, CURLOPT_POSTFIELDS should be used with JSON-encoded strings for JSON communication. Here's the modified code:

$data_string = json_encode($data);

$curl = curl_init('http://webservice.local/');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string)
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($curl);
$result = json_decode($result);
var_dump($result);
Copy after login

This code correctly sets the HTTP header to indicate JSON content and encodes the data before sending it as JSON.

Additional Note:

It's essential to ensure that the header('Content-type: application/json'); line appears only once on your web service page. If it's called multiple times, it may cause issues in sending the proper header information.

The above is the detailed content of How to Correctly Read and Parse JSON POST Data in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template