PHP code to get exchange rates between currencies

published Jun 23, 2005, last modified Jun 26, 2013

Given the DOMit! PHP DOM parser and an XML feed taken from the Federal Reserve Bank of New York, the following code will let you get exchange rates between two currency symbols (e.g. USD to EUR).

Please beware that my blogging software adds a backslash for every quote mark. You should promptly remove these before attempting to use this code.

require_once("xml_domit_parser.php");


function get_currency_exchange_array($location) {


global $_get_currencies_cache;
if ($_get_currencies_cache) { return $_get_currencies_cache; }
$data = file_get_contents($location);
$doc = new DOMIT_Document();
$doc->parseXML($data, true);

//crear un array vacio $moneda;
$moneda = array();
//traerme todos los frbny:series en una lista $list
$list = $doc->getElementsByTagName("frbny:Series");

//para cada elemento de $list:
foreach ($list->arNodeList as $element) {
    $UNIT = $element->getAttribute("UNIT");
    if (!$UNIT) continue;

    $frbny_CURR = $element->getElementsByTagName("frbny:CURR");
    if (!$frbny_CURR) continue;
    $frbny_CURR = $frbny_CURR->arNodeList;
    if (!$frbny_CURR) continue;
    $frbny_CURR = $frbny_CURR[0];
    if (!$frbny_CURR) continue;
    $frbny_CURR = $frbny_CURR->firstChild;
    if (!$frbny_CURR) continue;
    $frbny_CURR = $frbny_CURR->nodeValue;
    if (!$frbny_CURR) continue;

    $frbny_OBS_VALUE = $element->getElementsByTagName("frbny:OBS_VALUE");
    if (!$frbny_OBS_VALUE) continue;
    $frbny_OBS_VALUE = $frbny_OBS_VALUE->arNodeList;
    if (!$frbny_OBS_VALUE) continue;
    $frbny_OBS_VALUE = $frbny_OBS_VALUE[0];
    if (!$frbny_OBS_VALUE) continue;
    $frbny_OBS_VALUE = $frbny_OBS_VALUE->firstChild;
    if (!$frbny_OBS_VALUE) continue;
    $frbny_OBS_VALUE = $frbny_OBS_VALUE->nodeValue;
    if (!$frbny_OBS_VALUE) continue;

    // si el array $moneda no contiene un elemento (array) de nombre UNIT, crearlo como array vacio
    if (!array_key_exists($UNIT,$moneda)) $moneda[$UNIT] = array();
    // ahora si, le metemos el valúe al array
    $moneda[$UNIT][$frbny_CURR] = floatval( $frbny_OBS_VALUE );
}

$_get_currencies_cache = $moneda;
return $moneda;

}

function exchange_rate($file,$from_descriptor,$to_descriptor,$donotrecurse=false) {
# returns null if no exchange rate found

$moneda = get_currency_exchange_array($file);

if (array_key_exists($from_descriptor,$moneda)    array_key_exists($to_descriptor,$moneda[$from_descriptor])) {
     return $moneda[$from_descriptor][$to_descriptor];
}
elseif ($donotrecurse == false) {
     $value = exchange_rate($file,$to_descriptor,$from_descriptor,true);
     if (!$value) return;
     return 1.0/$value;
}

return;


}

Be nice to the Federal Reserve server, and do not fetch their XML feed each time you want to obtain exchange rates.