0

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.

1

2 Answers 2

1

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)
  ); 
};
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.