How to POST and GET JSON Data using PHP cURL

In this quick post I’ll talk about How to POST and GET JSON Data using PHP cURL, As you know cURL library is often used in PHP to send and receive data to other web host and often used by developer when working on web services because it is a great library to send and receive data. And if you are working on rich application then often need to post and get data to other server , Working with cURL and json is best approach that’s why Here I’ll show you How to POST and GET JSON Data using PHP cURL


POST/SEND JSON Data using PHP cURL

In the following example I am sending user info to other server by POST request, For demo first I created userInfo array then I converted array in json because jSON is the fastest data type to travel from one server to other server. then specify the URL where the JSON data need to be sent after that initiate new cURL resource using by curl_init() function in php,then attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option. Don’t forget to set Content-Type as application/json using CURLOPT_HTTPHEADER option.Finally curl_exec() function is used to execute your POST request

$url = 'https://api.example.com/';
$ch = curl_init($url);
$userData = array(
    'name' => 'Rohit Kumar',
    'email' => '[email protected]',
    'city'=>'Kanpur',
    'mobile'=>'0000000000'  
);
$dataString= json_encode(array("userData" => $userData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($dataString))                                                                       
);   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);



GET/RECEIVE JSON POST Data using PHP cURL

Now I’ll show you how to get json post data, You can simply use file_get_contents() to fetch json data then use json_decode() function in php to decode json data into array format.

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);



Posted in PHP