Update currency rates for your ecommerce website

public function updateExchangeRate(){
	// Fetch currency rate 
	if (time()-filemtime("eurofxref-daily.xml") > 36000) {
		$stuff = file("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
		$fh = fopen("eurofxref-daily.xml","w");
		foreach ($stuff as $line) { fputs($fh,$line); }
		fclose ($fh);
		$xld = "loaded afresh (and not cached)";
	} else {
		# .. or read from cache
		$stuff = file("eurofxref-daily.xml");
		$xld = "cached (and not loaded afresh)";
	}
	# $xld may be used in your output to inform you user or admin
	# Extract exchange rates
	$exchrate['EUR'] = 1.00;
	foreach ($stuff as $line) {			
		preg_match("/currency='([[:alpha:]]+)'/",$line,$gota);
		if (preg_match("/rate='([[:graph:]]+)'/",$line,$gotb)) {
			$exchrate[$gota[1]] = $gotb[1];
		}
	}
	$GBP_EUR = round(1 / $exchrate[GBP], 8);
	$GBP_USD = round($GBP_EUR * $exchrate[USD], 8);						
}

Leave a comment