PHP cURL tutorial

how to get data from api using curl in php

Welcome back to shortlearner.com, In this post we will see how to fetch record from a website by using cURL API. so before start this tutorial we should take an small overview of it, what is it , how does it works and its benefites.

PHP cURL tutorial

What is cURL

so basically cURL means client URL which allows us to connect with other URLs and use their responses in our code, and it is a library that allows to make HTTP requests in PHP.
in order to use PHP’s cURL functions we need to install the libcurl package in our server.
PHP also requires that we use libcurl 7.02-beta and higher and it is works from PHP version 4.3.0 or higher.
in easy way cURL is a way to hit an URL from our code to get a html response from it.

Also Read
How to Install PHP on CentOS.
How to Send Attachment on mail using PHP.

PHP Login Script With Remember me.
Unable to create a directory a wordpress error

How to integrate Razorpay Payment Gateway using PHP.
Change password using javascript, php and mysqli.
Password and Confirm Password Validation Using JavaScript

Check Email is Already Registered in Database using Ajax and JavaScript.
How to hide extension of html and php file.?

Now we understand the uses of cURL with a real life example. suppose you are a owner of 5 luxuries hotel and all are registered in some kind of OTA (online traveling agent) like make my trip, goibibo and travel guru.
you want to manage all the inventory and rates on their platforms according to season.

in this case you have perform this task in 2 ways. first and difficult one is you go to each and every OTA’s dashboard and manage inventory or rates or you can try to develop a platform to manage all the hotels by using API.

so if you have a knowledge of cURL funcationlity you will manage it easily by hitting client’s URL.

In the below code we fetch the record from jsonplaceholder.typicode.com/users by using cURL functionality and print it on our webpage.

<?php 
$ch = curl_init( );
curl_setopt($ch, CURLOPT_URL, "http://jsonplaceholder.typicode.com/users");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
            curl_close($ch); 
$response = json_decode($result);
//echo "<pre>";print_r($response);echo"</pre>";
foreach ($response as $key => $row) {
	echo $row->name."<br>";
}
?>

first of all we use curl_init() function, this function is use for initializes a new session.
curl_setopt() functions is ues for set URL.
CURLOPT_RETURNTRANSFER that will return the transfer as a string of the return value of curl_exec().
and curl_close() that is using for end the session.