user2465936
user2465936

Reputation: 1040

Php get particular value from xml node (calling node name)

Xml

<CRates>
    <Currencies>
        <Currency>
            <ID>AED</ID>
            <Units>1</Units>
            <Rate>0.17200000</Rate>
        </Currency>
        <Currency>
            <ID>ATS</ID>
            <Units>1</Units>
            <Rate>0.04102750</Rate>
        </Currency>
    </Currencies>
</CRates>

Want to get for example Rate value where ID is ATS

At the moment can get only in such way

$xmlDoc = simplexml_load_file('__joomla.xml');
echo $xmlDoc->Currencies->Currency[1]->Rate;

<ID>ATS</ID> is within the second <Currency>, so Currency[1]

Of course echo $xmlDoc->Currencies->Currency[ATS]->Rate; does not work. But is any simple way to get it work?

Seems need to use foreach and inside foreach if <ID> == ATS, echo <Rate>

Upvotes: 3

Views: 808

Answers (2)

Andrew G. Johnson
Andrew G. Johnson

Reputation: 26993

Try this:

// This way should work for all versions of PHP
$rate = false;
foreach ($xmlDoc->Currencies->Currency as $currency)
{
    if ((string)$currency->ID == 'ATS')
    {
        $rate = (string)$currency->Rate;
        break;
    }
}

// This way should work for newer versions of PHP only, I personally think that anonymous functions like this add to the readability which is why I included both options
$rate = call_user_func(function() use ($xmlDoc) {
    foreach ($xmlDoc->Currencies->Currency as $currency)
    {
        if ((string)$currency->ID == 'ATS')
            return (string)$currency->Rate;
    }
    return false;
});

// Using false to signify failure is the standard in PHP
if ($rate !== false)
    echo 'The rate is: ',$rate;
else
    echo 'Rate not found';

You may not need to cast to string but I believe if you don't you'll end up with SimpleXMLElement objects (or something with a similar name) rather than strings.

Upvotes: 3

Mark Baker
Mark Baker

Reputation: 212402

Perhaps using xpath, something like:

$xmlDoc = simplexml_load_file('__joomla.xml'); 
// find all currency records with code value of ATS
$result = $xmlDoc->xpath("Currencies/Currency/ID[.='ATS']/parent::*");  
print_r($result); 

gives

Array
(
    [0] => SimpleXMLElement Object
        (
            [ID] => ATS
            [Units] => 1
            [Rate] => 0.04102750
        )

)

while

$xmlDoc = simplexml_load_file('__joomla.xml'); 
print_r($xmlDoc); 
// find all currency records with code value of ATS
$rate = $xmlDoc->xpath("Currencies/Currency/ID[.='ATS']/parent::*"); 
print_r((float) $rate[0]->Rate); 

gives

0.0410275

Upvotes: 0

Related Questions