首頁  >  文章  >  後端開發  >  如何在 PHP 中使用 cURL 取得 API 回應?

如何在 PHP 中使用 cURL 取得 API 回應?

Linda Hamilton
Linda Hamilton原創
2024-10-25 07:01:02148瀏覽

How to Get API Responses Using cURL in PHP?

在PHP 中使用cURL 取得API 回應

在PHP 中,您可以建立一個獨立的類,其中包含透過cURL 呼叫API的函數並獲得響應。以下是實現此目的的方法:

<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>

要使用此類,請建立一個實例並呼叫 getResponse 函數,並傳入 API URL 作為參數。該函數將從 API 傳回回應。

以上是如何在 PHP 中使用 cURL 取得 API 回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn