"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Get API Responses Using cURL in PHP?

How to Get API Responses Using cURL in PHP?

Published on 2024-11-08
Browse:156

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:

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.

Release Statement This article is reprinted at: 1729746145 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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