如何从此xml中获取值

时间:2012-12-24 07:54:40

标签: php xml simplexml

我有来自外部网址http://www.xmlcharts.com/cache/precious-metals.xml

的xml文件
<prices>
<pricelist currency="usd">
<price timestamp="1356079920" per="ozt" commodity="gold">1649.45</price>
<price timestamp="1356079680" per="ozt" commodity="palladium">676.00</price>
<price timestamp="1356079740" per="ozt" commodity="platinum">1553.75</price>
<price timestamp="1356079860" per="ozt" commodity="silver">29.95</price>
</pricelist>
<pricelist currency="eur">
<price timestamp="1356079920" per="ozt" commodity="gold">1248.80</price>
<price timestamp="1356079680" per="ozt" commodity="palladium">511.80</price>
<price timestamp="1356079740" per="ozt" commodity="platinum">1176.34</price>
<price timestamp="1356079860" per="ozt" commodity="silver">22.68</price>
</pricelist>
<pricelist currency="chf">
<price timestamp="1356079920" per="ozt" commodity="gold">1507.76</price>
<price timestamp="1356079680" per="ozt" commodity="palladium">617.93</price>
<price timestamp="1356079740" per="ozt" commodity="platinum">1420.28</price>
<price timestamp="1356079860" per="ozt" commodity="silver">27.38</price>
</pricelist>
</prices>

我已经使用PHP通过

加载它
$xmlobj = simplexml_load_file($feedurl);
print_r($xmlobj->pricelist);

输出如下:

SimpleXMLElement Object ( [pricelist] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [currency] => usd ) [price] => Array ( [0] => 1649.45 [1] => 676.00 [2] => 1553.75 [3] => 29.95 ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [currency] => eur ) [price] => Array ( [0] => 1248.80 [1] => 511.80 [2] => 1176.34 [3] => 22.68 ) ) [2] => SimpleXMLElement Object ( [@attributes] => Array ( [currency] => chf ) [price] => Array ( [0] => 1507.76 [1] => 617.93 [2] => 1420.28 [3] => 27.38 ) ) ) )

我已尝试过$xmlobj->pricelist,但无法获得价格值......

3 个答案:

答案 0 :(得分:2)

$xml = simplexml_load_file('http://www.xmlcharts.com/cache/precious-metals.xml');

foreach($xml as $pricelist) {
    // if($pricelist->attributes()->currency == 'usd')
    foreach($pricelist as $price) {
        echo $price[0].' ';
    }
}

答案 1 :(得分:0)

如果您真的检查print_r($xmlobj->pricelist);的输出,可以看到 抓取每个项目的价格。尝试将pricelist视为对象来访问价格。通过$xmlobj->pricelist->price[1]访问价格并查看是否有效。

我这样说是因为$xmlobj->pricelist->price数组包含您正在寻找的机器人。

答案 2 :(得分:0)

$load_xml = simplexml_load_file("http://www.xmlcharts.com/cache/precious-metals.xml"); 
echo $load_xml->pricelist[0]->price[0]; //is gold

echo $load_xml->pricelist[0]->price[1]; //is palladium
echo $load_xml->pricelist[0]->price[2]; //is platinum
echo $load_xml->pricelist[0]->price[3]; //is silver