What are the potential pitfalls of using PHP to fetch and display currency exchange rates from external sources?
One potential pitfall of using PHP to fetch and display currency exchange rates from external sources is that the external API may have rate limits or require authentication, which can lead to errors or incomplete data retrieval. To solve this, you can implement error handling and authentication methods in your PHP code to ensure smooth data retrieval from the external API.
<?php
// Set API endpoint and authentication credentials
$api_url = 'https://api.example.com/exchangerates';
$api_key = 'your_api_key';
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $api_key
));
// Execute cURL session
$response = curl_exec($ch);
// Check for errors
if($response === false){
echo 'Error: ' . curl_error($ch);
}
// Close cURL session
curl_close($ch);
// Display exchange rates
echo $response;
?>