Curl allows users to send JSON data to an HTTP server; In this tutorial guide, we will show you how to POST JSON data with PHP curl.
How to POST JSON Data using PHP cURL
Here are steps to post JSON data using curl in PHP:
Step 1: Set up the JSON data
Create a simple JSON object containing two key-value pairs:
$data = array(
'name' => 'Dev Smith',
'email' => '[email protected]'
);
$json = json_encode($data);
The json_encode
function converts the array into a JSON string.
Step 2: Set up the cURL request
Set up the cURL request with URL, type, method, and header to send the JSON data:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
));
Step 3: Execute the cURL request
Run the request using the curl_exec
function:
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
echo 'Response: ' . $response;
}
curl_close($ch);
Conclusion
You have learned how to set up a curl request with type, method, URL, and other parameters and the cur_exe() function to run a curl request to send data to the server.