Use PHP to pull API data with cURL

I have been working with PHP for quite a long. Having been really busy with iOS due to my job I haven't really had any time to pay attention to the PHP recently. However, I will begin writing these series of PHP tricks blogs to share some of the new tricks I learned while working on PHP while back. Hope they will be useful to someone in the future.

Today, I will talk about how you can use PHP and cURL to pull the data from API. cURL is a library to pull data from remote APIs. As per the description from Here, I quote

Curl is a tool and libcurl is a library for transferring data with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, GOPHER, TFTP, SCP, SFTP, TELNET, DICT, LDAP, LDAPS, FILE, IMAP, SMTP, POP3, RTSP and RTMP. libcurl offers a myriad of powerful features

So let's get to the simple part. I use following cURL code with PHP to pull the data from API as follows :

$curl = curl_init();  
$remote_url = "<insert_your_remote_API_URL_Here>";
$method="GET"; // Could be POST, PUT, DELETE or HEAD  
curl_setopt($curl, CURLOPT_URL, $remote_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);  
$requestResult = curl_exec($curl);  
if ($requestResult === false) {
    throw new Exception('cURL error: ' . curl_error($crl));
    print_r('Failed to get data from URL. Failed with error : ' . curl_error($curl));
$response = json_decode($requestResult,true);

Here response is your final value of response object returned by the remote server. Wasn't very hard, was it? Let me know if you have any other questions about retrieving data using cURL.

I would love to hear your thoughts about it!

Jayesh Kawli

I am a web and mobile developer working at Wayfair in Boston, MA. I come to learn so many things during course of life and I write about things which helped me and feel like they can help others too.

Subscribe to Fresh Beginning

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!