How To Post And Receive JSON Data Using Curl In PHP

admin_img Posted By Bajarangi soft , Posted On 16-09-2020

In this we are going to discuss how we can POST and Receive JSON Data using cURL in PHP. Sending and Receiving JSON data via POST Request is most important functionality in PHP. It’s make easy to POST JSON data to APIs url and receive response in JSON data format.

post-and-receive-json-data

Post And Receive Json Data
Follow this example:

 I will show you HTTP POST request and send JSON data to URL with cURL function.
      - First we will specify URL ($url) where the JSON data need to be send.
      -Initiate cURL resource using curl_init().
      -
encode PHP array data into aJSON string using json_encode().
      -
Attach JSON data to the POSt field using the CURLOPT_POSTFIELDS option.
      -set header option to Content-Type: application/json
      -
 Return response as string CURL_RETURNTRANSFER option
      - Finally curl_exec() function is used to execute the POST request api url.


You need to create index.php file
 We will pass POST data on API URL as JSON format
index.php
<?php



$id=1;
$name='Jone';
$address='Nagarbhavi banglore';
$phone=1234567890;

$url="http://localhost/Curl/post_data/auth.php";

$data = array("id" => $id, "name" => $name, "address" => $address,"phone"=>$phone);
$ch = curl_init( $url );
$payload = json_encode( array( "customer"=> $data ) );

curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
echo "<pre>" . $result. "</pre>";

?>

auth.php
We will Receive JSON POST data using PHP
<?php
header("Content-Type:application/json");
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
?>

Related Post