I used the following PHP to pull data from the ECB as Stefan Gehrig suggested.
<?php
try {
$xml_string = file_get_contents("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
$xml = new SimpleXMLElement($xml_string);
$cxml = $xml->xpath('//*[@currency]');
//anchored to USD in this case
$usx = $xml->xpath('//*[@currency="USD"]');
$base = floatval(strval($usx[0]['rate']));
//create a simple associative array with the 3-letter code
//as the key and the rate as the value
$c_arr = array();
foreach ($cxml as $c) {
$cur = strval($c['currency']);
$rate = floatval(strval($c['rate']))/$base;
$c_arr[$cur] = $rate;
}
//add the euro since it's assumed as the base rate for the ECB
$c_arr['EUR'] = 1/$base;
$currency_json = json_encode($c_arr);
//write to file
$file = "currency.json";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $currency_json);
fclose($fh);
echo $currency_json;
} catch (Exception $e) { echo $e; }
?>
It writes a JSON file that I include as a JavaScript variable:
<script type="text/javascript">
var data = <?php include('currency.json'); ?>;
</script>
I can then easy grab the data using the 3-letter currency code (e.g., data['GBP']
) with JavaScript when a currency change is requested.
I use a Cron Job to update the JSON once a day, so it's not making a call each time the page is visited.