在 PHP 中使用 cURL 获取 API 响应
在 PHP 中,您可以创建一个独立的类,其中包含通过 cURL 调用 API 的函数并获得响应。以下是实现此目的的方法:
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;
}
}
要使用此类,请创建一个实例并调用 getResponse 函数,并传入 API URL 作为参数。该函数将从 API 返回响应。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3