使用simplexml php从xml获取特定标记

时间:2014-01-08 14:45:10

标签: php xml simplexml

我有这个XML我试图解析:http://rss.desura.com/games/feed/rss.xml?cache=sale

里面有这个:

<saleprices>
<price currency="USD">6.79</price>
<price currency="AUD">6.79</price>
<price currency="EUR">5.09</price>
<price currency="GBP">4.42</price>
</saleprices>

通常在php中使用simplexml作为标签你会使用类似$ game-&gt; {'price'}的东西,但是如何从该列表中选择像USD这样的特定代码呢?我之前没有使用过在标记内包含字符串的XML。

我正在加载和读取这样的XML:

$url = 'http://rss.desura.com/games/feed/rss.xml?cache=sale';
$xml = simplexml_load_string(file_get_contents($url));

foreach ($xml->browse->game as $game)
{

1 个答案:

答案 0 :(得分:4)

<?php

$url = 'http://rss.desura.com/games/feed/rss.xml?cache=sale';
$xml = simplexml_load_string(file_get_contents($url));

foreach ($xml->browse->game as $game)
{
    foreach($game->saleprices->price->attributes() as $a => $b) {
       echo "Price: " . $b . " ";
       echo $game->saleprices->price . "<br />";
    }
}

将输出:

Price: USD 7.99
Price: USD 2.49
Price: USD 13.99
Price: USD 4.99
......

或者像这样得到每种货币和价格:

<?php

$url = 'http://rss.desura.com/games/feed/rss.xml?cache=sale';
$xml = simplexml_load_string(file_get_contents($url));

foreach ($xml->browse->game as $game)
{
    echo "<br />Prices:<br />";
    foreach($game->saleprices->price as $a) {
        foreach($a->attributes() as $b => $c) {
           echo $c . " ";
           echo $a . "<br />";
        }
    }
}

将输出:

Prices:
USD 7.99
AUD 7.99
EUR 7.99
GBP 7.99

Prices:
USD 2.49
AUD 2.99
EUR 1.99
GBP 1.75

Prices:
USD 13.99
AUD 15.49
EUR 9.99
GBP 8.49