Home  >  Article  >  Backend Development  >  How to Get API Responses Using cURL in PHP?

How to Get API Responses Using cURL in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 07:01:02148browse

How to Get API Responses Using cURL in PHP?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn