我有这样的xml。有些物品价格较旧,有些物品没有。
<product>
<item>
<name>product 1</name>
<price type="old">100</price>
<price type="new">50</price>
</item>
<item>
<name>product 2</name>
<price type="old">100</price>
<price type="new">50</price>
</item>
<item>
<name>product 3</name>
<price type="new">50</price>
</item>
</product>
我想遍历每个项目但只能获得那些类型=&#34; old&#34;项目
答案 0 :(得分:1)
可以使用xpath直接获取项目:
获取item
文档元素
product
个孩子
/product/item
具有price
子元素
/product/item[price]
其中属性type
的值为old
/product/item[price[@type="old"]]
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
$items = $xpath->evaluate('/product/item[price[@type="old"]]');
foreach ($items as $item) {
var_dump(
$xpath->evaluate('string(name)', $item)
);
};
答案 1 :(得分:0)
尝试使用xpath
$xml = new SimpleXmlElement($str);
$result = $xml->xpath('/product/item');
$items = array();
foreach($result as $res){
$price = $res->xpath('price');
foreach($price as $p){
if($p['type']=='old'){
$items[] = $res;
}
}
}
请参阅演示here