How to Call API in PHP Using Curl

In this article we are going to learn how to call an API in PHP file using cURL method. PHP provides effortless inbuilt method cURL to call API and process its response.

What is cURL in PHP?

cURL is the method to request web URLs or APIs in PHP. It helps to get data from other sources or websites rather than the only database.

Must Read: How to Create a Simple PHP REST API

How To Use cURL To Call APIs in PHP?

cURL is an effortless method in PHP to call an API. We have to use the curl function with some parameters to call an API.

Example

This example explains the simplest way to call an API using cURL in PHP.

<?php
header("Access-Control-Allow-Origin: *"); # enable Cross Origin [CORS]
$url = 'http://dummy.restapiexample.com/api/v1/employees'; # API Link

$ch = curl_init(); # initialize curl object
curl_setopt($ch, CURLOPT_URL, $url); # set url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); # receive server response
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); # do not verify SSL

$data = curl_exec($ch); # execute curl
$httpstatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); # http response status code
curl_close($ch); # close curl

echo "Errors: ".curl_error($ch)."<br>"; # Print errors if any
echo "Status: ".$httpstatus."<br>"; # Print Response Status Code
var_dump($data); # Print Response Data
?>

Read Also: PHP Object to JSON Object [Encode & Decode]

Conclusion

I hope now you have a complete understanding of cURL and request of APIs in PHP. There are lots of other features of cURL which are useful to manage headers, data and responses of the request.

Keep exploring, Enjoy Coding ๐Ÿ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *

Read previous post:
json encode-decode php
PHP Object to JSON Object [Encode & Decode]

Here, we are going to see how JSON encoding and decoding are performed in PHP with some examples. JSON encode...

Close