尝试从XML属性获取特定值

时间:2017-02-12 22:14:08

标签: php simplexml

尝试通过以下链接抓取宜家页面:

http://www.ikea.com/it/it/catalog/products/60255550/?type=xml&dataset=prices

我想要刮取商品的价格,但是在xml文件中,价格会在未格式化后显示,而一次显示旁边的欧元符号。我希望特别贬低价格正常的未格式化价值。

<prices>
<normal>
<priceNormal unformatted="44.99">€ 44,99</priceNormal>
<pricePrevious/>
<priceNormalPerUnit/>
<pricePreviousPerUnit/>
</normal>

我的代码根本没有回应价格,不知道我哪里出错了:(

$string = 'http://www.ikea.com/it/it/catalog/products/60255550/?type=xml&dataset=prices';

$xml=simplexml_load_file($string) or die("Error: Cannot create object");
//print_r($xml);

echo $xml->product->prices;

2 个答案:

答案 0 :(得分:1)

尝试使用var_dump()代替print_r()来查看$xml的值。这有点令人费解,但你会在这个位置找到你想要的数据:

$xml->products[0]->product->items[0]->item->prices->normal->priceNormal[0];

答案 1 :(得分:1)

您应该可以通过

获得价格
$xml->products->product->items->item->prices->normal->priceNormal
$xml->products->product->items->item->prices->normal->priceNormal->attributes()->unformatted

如果你需要迭代结果集,你可以通过迭代分解你期望倍数的地方......

foreach( $xml->products->product as $product )
{
  echo $product->name;
  foreach( $product->items->item as $item )
  {
    echo $item->name;
    echo $item->prices->normal->priceNormal;
    echo $item->prices->normal->priceNormal->attributes()->unformatted;
  }
}