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

时间:2013-08-01 19:06:32

标签: php xml

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;不起作用。但是有什么简单的方法可以让它发挥作用吗?

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

2 个答案:

答案 0 :(得分:3)

试试这个:

// 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对象(或类似名称的东西)而不是字符串。

答案 1 :(得分:0)

也许使用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