PHP cURL POST JSON Data Example

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.

More PHP Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *