I need help with this issue, it seems I can't get targetCurrency
out of the SimpleXMLElement Object
XML
<channel>
<title>XML ~~ Exchange Rates ~~</title>
<language>en</language>
<item>
<baseCurrency>USD</baseCurrency>
<targetCurrency>EUR</targetCurrency>
<targetName>Euro</targetName>
<exchangeRate>0.90900497</exchangeRate>
</item>
</channel>
$url = "http://www.floatrates.com/daily/usd.xml";
$xml = simplexml_load_file($url);
foreach($xml->item as $rate){
$rate = (string) $rate->exchangeRate;
$curr_code = (string) $rate->targetCurrency;
$money[] = array('rate' => $rate, 'curr_code' => $curr_code);
}
print_r($money);
$money
outputs:
Array
(
[0] => Array
(
[rate] => 0.90947603
[curr_code] =>
)
[1] => Array
(
// ...and so on...
[curr_code]
should output the ISO code, EUR, USD,AUD etc.
How can I fix it?
CodePudding user response:
Try it using xpath instead:
$items = $xml->xpath("//item");
foreach($items as $item){
$rate = $item->xpath('.//exchangeRate')[0];
$curr_code = $item->xpath('.//targetCurrency')[0];
$money[] = array('rate' => $rate, 'curr_code' => $curr_code);
}
print_r($money);
The output should be as exptected.