What are the best practices for using Curl or APIs in PHP to gather data from websites?

When using Curl or APIs in PHP to gather data from websites, it is important to handle errors gracefully, set appropriate headers, and properly parse the response data. It is also a good practice to use secure connections (https) when making requests to ensure data integrity.

<?php
$url = 'https://example.com/api/data';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Authorization: Bearer YOUR_API_KEY'
));

$response = curl_exec($ch);

if($response === false){
    echo 'Curl error: ' . curl_error($ch);
} else {
    $data = json_decode($response, true);
    print_r($data);
}

curl_close($ch);
?>