How can cURL and file_get_contents be used to make requests to external APIs in PHP?
When making requests to external APIs in PHP, you can use either cURL or file_get_contents function. cURL is a more powerful and flexible option that allows you to set various options like headers, authentication, and more. On the other hand, file_get_contents is simpler to use but may not provide as much control as cURL. Here is a code snippet demonstrating how to use cURL to make a GET request to an external API:
$url = 'https://api.example.com/data';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if($response === false){
echo 'cURL error: ' . curl_error($ch);
}
curl_close($ch);
echo $response;
```
And here is a code snippet using file_get_contents to achieve the same:
```php
$url = 'https://api.example.com/data';
$response = file_get_contents($url);
if($response === false){
echo 'Error fetching data';
} else {
echo $response;
}