1

我有来自外部 url 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了,但无法获得价格价值...

4

3 回答 3

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].' ';
    }
}
于 2012-12-24T08:06:07.130 回答
0

如果你真的检查你的输出,print_r($xmlobj->pricelist);你会发现它正在抓取每件商品的价格。尝试通过将pricelist其视为对象来访问价格。通过以下方式访问价格:$xmlobj->pricelist->price[1]看看是否可行。

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

于 2012-12-24T07:59:10.100 回答
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
于 2013-01-20T17:00:31.690 回答