k12anime
k12anime

Reputation: 1

Conditional inside loop on an xml PHP

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

Answers (2)

ThW
ThW

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

Nouphal.M
Nouphal.M

Reputation: 6344

Try using 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;
   }
  }
}

See demo here

Upvotes: 0

Related Questions