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.
<?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>";
?>
<?php
header("Content-Type:application/json");
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
?>