How to POST JSON Data with PHP cURL, Return in Readable Format
Your code is not posting JSON data correctly, even at your server, it returns an empty array. To implement REST using JSON as in Shopify's API, we need to address this issue.
Correcting the POST Request
To fix the problem, we need to encode the entire POST data in JSON, not just the "customer" field. Modify your code as follows:
$ch = curl_init($url); # Setup request to send JSON via POST. $payload = json_encode(array("customer" => $data)); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); # Return response instead of printing. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); # Send request. $result = curl_exec($ch); curl_close($ch); # Print response. echo "<pre class="brush:php;toolbar:false">$result";
Accessing the POST Data
On the other page, we cannot use $_POST to retrieve the POST data because of server-side parsing. Instead, use file_get_contents("php://input"), which contains the POSTed JSON. To view the data in a readable format:
echo '<pre class="brush:php;toolbar:false">'.print_r(json_decode(file_get_contents("php://input")),1).'';
Additional Considerations
The above is the detailed content of Why is my PHP cURL POST request returning an empty array when sending JSON data?. For more information, please follow other related articles on the PHP Chinese website!