Getting API Responses Using cURL in PHP
In PHP, you can create a standalone class that includes a function to call an API via cURL and obtain the response. Here's how you can achieve this:
<code class="php">class ApiRequest { public function getResponse($url) { // Set cURL options $options = array( CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 10, CURLOPT_ENCODING => "", CURLOPT_AUTOREFERER => true, CURLOPT_CONNECTTIMEOUT => 120, CURLOPT_TIMEOUT => 120, ); // Initialize cURL $ch = curl_init($url); curl_setopt_array($ch, $options); // Execute cURL and get the response $response = curl_exec($ch); curl_close($ch); // Return the response return $response; } }</code>
To use this class, create an instance and call the getResponse function, passing in the API URL as an argument. The function will return the response from the API.
The above is the detailed content of How to Get API Responses Using cURL in PHP?. For more information, please follow other related articles on the PHP Chinese website!