John Davidson

simplexml - Get values from SimpleXMLElement Object for php array

0 comments
Message:


I need help with this issue, it seems I can't get targetCurrency out of the SimpleXMLElement Object


$xmlString = <<<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>
XML;

$xml = simplexml_load_string($xmlString);

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);

This outputs:


Array
(
[0] => Array
(
[rate] => 0.90947603
[curr_code] =>
)
)

[curr_code] should output 'EUR'.


How can I fix it?



My Answer:
You are trying to access the targetCurrency element from the $rate variable, which is already set to the exchangeRate element. Instead, you should access the targetCurrency element directly from the $xml object. Here is the corrected code:

php
$xmlString = <<
XML ~~ Exchange Rates ~~
en

USD
EUR
Euro
0.90900497


XML;

$xml = simplexml_load_string($xmlString);

$money = array();

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);


This should now output:


Array
(
[0] => Array
(
[rate] => 0.90900497
[curr_code] => EUR
)
)


Now the curr_code should output 'EUR' as expected.

Rate this post

5 of 5 based on 6441 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us