Php从xml节点(调用节点名称)获取特定值


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>

想要获得例如Rate值,其中ID是ATS

目前只能通过这种方式获得

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

<ID>ATS</ID>在第二个<Currency>内,因此Currency[1]

当然echo $xmlDoc->Currencies->Currency[ATS]->Rate;不起作用。但有什么简单的方法可以让它发挥作用吗?

如果<ID>==ATS,则似乎需要使用foreach和内部foreach,echo <Rate>

试试这个:

// 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';

您可能不需要强制转换为字符串,但我相信如果不这样做,您最终会得到SimpleXMLElement对象(或类似名称的对象),而不是字符串。

也许使用xpath,类似于:

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

给出

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

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

给出

0.0410275