PHP简单XML解析

发布于 2024-08-25 06:40:25 字数 567 浏览 5 评论 0原文

我需要货币兑换,欧元兑换美元。
欧洲中央银行在此提供利率:
http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
我可以使用第一个节点获取美元汇率,但如果他们更改顺序怎么办?
我需要更可靠的东西吗?我不知道怎么办..

$xml = @simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
echo "dollar: " . $xml->Cube->Cube->Cube[0]->attributes()->rate;

I need currency conversion, euro to dollar.
The European Central bank provides the rates here:
http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
I can get the USD rate by using the first node, but what if they change the order?
Do I need something more reliable? I have no idea how..

$xml = @simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
echo "dollar: " . $xml->Cube->Cube->Cube[0]->attributes()->rate;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

樱花坊 2024-09-01 06:40:25

只需使用 XPath 获取属性 @currency 等于“USD”的任何节点即可。

$xref  = simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
$nodes = $xref->xpath('//*[@currency="USD"]');

echo $nodes[0]['rate'];

Just use XPath to get any node with the attribute @currency equal to "USD", that will do the trick.

$xref  = simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
$nodes = $xref->xpath('//*[@currency="USD"]');

echo $nodes[0]['rate'];
撩起发的微风 2024-09-01 06:40:25

他们在此页面提供示例代码:

只需单击选项卡对于开发人员

还有一个(未维护的)PEAR 汇率包

如果他们更改顺序,您不必担心。如果他们这样做,他们就会这样做。

They provide example code at this page:

Just click the tab For Developers

There is also an (unmaintained) PEAR Package for Exchange Rates

You should not bother if they change the order. If they do, they do.

后知后觉 2024-09-01 06:40:25

您可以使用 foreach 迭代 simpleXML 对象

foreach( $xml->Cube->Cube as $cube ) {
    if( isset( $cube->attributes()->rate ) ) {
         $rate = $cube->attributes()->rate; 
    }    
}

You can iterate through simpleXML objects with a foreach

foreach( $xml->Cube->Cube as $cube ) {
    if( isset( $cube->attributes()->rate ) ) {
         $rate = $cube->attributes()->rate; 
    }    
}
ま昔日黯然 2024-09-01 06:40:25

你可以使用xpath

$rate = $xml->xpath("//Cube[currency='USD']/rate")

You can use xpath

$rate = $xml->xpath("//Cube[currency='USD']/rate")
可可 2024-09-01 06:40:25

你是对的。目前,您假设第 0 个条目为 USD,如果将来订单发生变化,您的假设就会失败。因此,为了使您的应用程序独立于订单,您可以在循环中检查 currency 属性。当您找到价值“USD”的那一刻,您就可以获得其相应的rate属性。

You are right. Currently you are assuming the 0th entry to be USD and if the order changes in the future your assumption fails. So to make your application independent of the order, you can check for the currency attribute in a loop. The moment you find one with value "USD" you can get its corresponding rate attribute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文