Skip to content
Advertisement

Get values from SimpleXMLElement Object for php array

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?

Advertisement

Answer

You are using the same variable name for two different things:

foreach($xml->item as $rate){
    // at this point, $rate is the <item> element

    $rate       = (string) $rate->exchangeRate;
    // now $rate is a string with the exchange rate

    $curr_code  = (string) $rate->targetCurrency;
    // so now this won't work

    $money[] = array('rate' => $rate, 'curr_code' =>  $curr_code);
}

If you were running with display_errors switched on or checking your logs, you would have seen a message like this:

Notice: Trying to get property ‘targetCurrency’ of non-object

Or in PHP 8, this:

Warning: Attempt to read property “targetCurrency” on string


The fix is simply to name your variables more carefully:

foreach($xml->item as $itemElement){
    $rate = (string) $itemElement->exchangeRate;
    $curr_code  = (string) $itemElement->targetCurrency;
    $money[] = array('rate' => $rate, 'curr_code' =>  $curr_code);
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement