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:
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;
}
}
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3