What are some best practices for handling currency conversion in PHP?
Currency conversion in PHP can be handled by using external APIs or libraries that provide up-to-date exchange rates. One popular option is to use the `exchangeratesapi.io` API to fetch exchange rates and perform the conversion calculations in your PHP code.
// Function to convert currency using exchangeratesapi.io API
function convertCurrency($amount, $from, $to) {
$apiKey = 'YOUR_API_KEY';
$url = "https://api.exchangeratesapi.io/latest?base=$from&symbols=$to&access_key=$apiKey";
$response = file_get_contents($url);
$data = json_decode($response, true);
$exchangeRate = $data['rates'][$to];
$convertedAmount = $amount * $exchangeRate;
return $convertedAmount;
}
// Example usage
$amount = 100;
$fromCurrency = 'USD';
$toCurrency = 'EUR';
$convertedAmount = convertCurrency($amount, $fromCurrency, $toCurrency);
echo "$amount $fromCurrency is equal to $convertedAmount $toCurrency";