PHP is the most used back-end language for websites because of its flexibility and long-lasting support. PHP provides effortless inbuilt methods to call API and process its response. In PHP, we can use cURL to request API.
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.
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 More: How to Create a Simple PHP REST API
Conclusion
I hope now you have a complete understanding of cURL and request of APIs in PHP.
Enjoy Coding π