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

How to Get API Responses Using cURL in PHP?

Linda Hamilton
Release: 2024-10-25 07:01:02
Original
239 people have browsed it

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template