How to Post JSON Data using cURL in PHP
Table of Contents
JSON is the most popular data format on the web because it is natively supported in JavaScript and human-readable.
As such, many APIs support the ability to send and receive JSON data.
In this tutorial, we will learn how to send JSON data to a URL using cURL in PHP.
Sending JSON Data to a URL
To send JSON data to a URL, first let's define the array we want to send:
PHP$data = [
'name' => 'John Doe',
'age' => 30
];
Now let's encode the array as JSON:
PHP$json = json_encode($data);
Not that we have our JSON, let's initialize a cURL request:
PHP$ch = curl_init();
Now let's apply a few options:
PHPcurl_setopt($ch, CURLOPT_URL, 'https://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, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
]);
Finally, let's execute the request:
PHP$output = curl_exec($ch);
Now, we can close the cURL request:
PHPcurl_close($ch);
Taken all together, we can write a reusable function for this:
PHP$data = [
'name' => 'John Doe',
'age' => 30
];
function post_json($url, $data) {
$json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
]);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$output = post_json('https://example.com/api', $data);
echo $output;
Conclusion
In this post, we learned how to send JSON data to a URL using cURL in PHP.
Simply initialize a new cURL request, apply a few options, and execute the request with the given url and data.
Thanks for reading!
Then, we can close the cURL request and return the output.
- Managing PHP Dependencies with Composer
- Getting Started with Express
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor