How can PHP scripts be optimized to efficiently handle and process currency exchange rate data?

To efficiently handle and process currency exchange rate data in PHP scripts, one can utilize caching mechanisms to store and retrieve exchange rates, minimizing the need for repeated API calls. Additionally, optimizing database queries and using proper data structures can help improve performance when working with large amounts of exchange rate data.

// Example of caching exchange rates in PHP using file caching

// Function to get exchange rate from API or cache
function getExchangeRate($currency) {
    $cacheFile = 'exchange_rates.json';

    if (file_exists($cacheFile) && time() - filemtime($cacheFile) < 3600) {
        $exchangeRates = json_decode(file_get_contents($cacheFile), true);
    } else {
        // Make API call to get exchange rates
        $exchangeRates = ['USD' => 1.0, 'EUR' => 0.85, 'GBP' => 0.75];

        file_put_contents($cacheFile, json_encode($exchangeRates));
    }

    return $exchangeRates[$currency];
}

// Example usage
$usdToEur = getExchangeRate('EUR');
echo '1 USD is equal to ' . $usdToEur . ' EUR';