<?php
//Reads currency conversion rates to AUD from RBA data in XML format
//Reserve Bank of Australia conversion rates XML link: http://www.rba.gov.au/rss/rss-cb-exchange-rates.xml
//
//By Kevin Koster, 2017. Free for any use.

//Lists RBA Currency conversions in array: $curarray[TARGETCURRENCY]
function currencylist($currencyfile)
 {
  global $curarray;
  function startelement(&$parser, &$elname, &$attribute)
  {
   global $nextiscurrency, $nextisvalue;
   if ($elname === "CB:VALUE") //Contents is the currency conversion rate
    $nextisvalue = TRUE;
   elseif ($elname === "CB:TARGETCURRENCY") //Contents is the target currency ID
    $nextiscurrency = TRUE;
  }

  function endelement()
  {
  }

  function characterdata(&$parser, &$contents)
  {
   global $nextiscurrency, $nextisvalue, $curarray;
    if ($nextisvalue)
    {
     $curarray['x'] = (float)$contents;
     $nextisvalue = FALSE;
    }
    elseif ($nextiscurrency)
    {
     $curarray[$contents] = $curarray['x'];
     $nextiscurrency = FALSE;
    }
  }

  $xmlfile = file_get_contents($currencyfile);
  $currencyparser = xml_parser_create('UTF-8');
  xml_set_element_handler($currencyparser, 'startelement', 'endelement');
  xml_set_character_data_handler($currencyparser, 'characterdata');

  if (!xml_parse($currencyparser, $xmlfile, TRUE))
   error_log ( "Currency Converter: XML Error: " . xml_error_string(xml_get_error_code($currencyparser)) .
   ", at line: " . xml_get_current_line_number($currencyparser) );

  xml_parser_free($currencyparser);

  unset($curarray['x'], $curarray['XXX'], $curarray['XDR']); //Remove unwanted entries from array
  return $curarray;
 }
?>

