Reputation: 1
I have an xml like this. There are items with old price and some dont have.
<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>
I want to iterate through each item but only get those that have type="old" items.
Upvotes: 0
Views: 86
Reputation: 19492
It is possible to use xpath to fetch the items directly:
Get all item
children inside the product
document element
/product/item
that have a price
child element
/product/item[price]
where the attribute type
has the value old
/product/item[price[@type="old"]]
Example: https://eval.in/106865
$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)
);
};
Upvotes: 1