3

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>

想要获得例如ATSRate在哪里的值ID

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

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

<ID>ATS</ID>在秒内<Currency>,所以Currency[1]

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

似乎需要使用foreachand inside foreach if <ID>== ATS, echo<Rate>

4

2 回答 2

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 对象(或具有相似名称的对象)而不是字符串。

于 2013-08-01T19:11:21.283 回答
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
于 2013-08-01T19:18:25.597 回答