How can cURL be used to interact with APIs in PHP?

To interact with APIs in PHP using cURL, you can make HTTP requests to the API endpoints and handle the responses accordingly. cURL is a powerful library that allows you to send and receive data over various protocols. You can use cURL functions in PHP to make GET, POST, PUT, DELETE requests to APIs and process the responses.

// Initialize cURL session
$ch = curl_init();

// Set cURL options for the API request
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the cURL request
$response = curl_exec($ch);

// Close cURL session
curl_close($ch);

// Process the API response
if($response) {
    $data = json_decode($response, true);
    // Handle the API response data here
} else {
    // Handle cURL error
    echo 'cURL error: ' . curl_error($ch);
}