How to Post JSON Data With PHP Curl

As a web developer, you may have come across a scenario where you need to send data in JSON format to a server.

There are different ways to do this, but one of the most common and efficient methods is to use PHP cURL.

In this tutorial, we’ll discuss how to send JSON data with PHP cURL, including code examples to help you get started.


What is cURL in PHP?

cURL stands for “client for URLs”.

It is a command-line tool that allows you to transfer data from or to a server using various protocols, including HTTP and HTTPS.

With PHP, you can use cURL to send and receive data from a server in a variety of formats, including JSON.

Why Use cURL in PHP to Send JSON Data?

cURL in PHP is a powerful tool for sending and receiving data from a server.

It allows you to send data in different formats, including JSON, and to receive data in a variety of formats as well.

Additionally, cURL supports various protocols, including HTTP and HTTPS, so you can use it to send and receive data over secure connections.

How to Send JSON Data with PHP cURL

To send JSON data with PHP cURL, you need to use the CURLOPT_POSTFIELDS option to set the data to be sent in JSON format.

The following code example shows you how to send JSON data with PHP cURL:

<?php

$data = array("name" => "John Doe", "age" => 25);
$data = json_encode($data);

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://www.example.com/api/data",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $data,
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);

curl_close($curl);

echo $response;

?>

In this code, we first create an array of data to be sent. We then use the json_encode function to convert the data to a JSON string.

We then initialize cURL and set the various options for the request, including the URL to send the data to, the data to be sent in JSON format, and the content type of the data to be sent.

Finally, we send the request and print the response from the server.


Conclusion

Sending JSON data with PHP cURL is a straightforward process.

With a few lines of code, you can send and receive data in JSON format using PHP cURL.

Whether you’re building an API or working with data from a server, cURL in PHP can be a valuable tool in your arsenal.