0

I want to remove the element of the XML file under certain condition:

example.xml:

<all>
- <item>
  <ProductID>46121</ProductID> 
  <Price1>50</Price1> 
  </item>
- <item>
  <ProductID>51151</ProductID> 
  <Price1>20</Price1> 
  </item>
</all>

php:

<?php
$xml = simplexml_load_file('example.xml');
foreach ($xml->item as $item) {
$price  = $item->Price1;
if ($price < 50 ) { REMOVE THIS ITEM  } 
}
$xml->asXML("result.xml");
?>

I want if the price is less than 50 REMOVE THIS ITEM

result.xml to be:

<all>
- <item>
  <ProductID>46121</ProductID> 
  <Price1>50</Price1> 
  </item>
</all>
ilia2
  • 11
  • 5
  • 3
    Possible duplicate of [Remove a child with a specific attribute, in SimpleXML for PHP](http://stackoverflow.com/questions/262351/remove-a-child-with-a-specific-attribute-in-simplexml-for-php) – John V. Dec 06 '15 at 09:52

2 Answers2

1

You are looking for removeChild in the DOM extension.

With dom_import_simplexml() you can convert your SimpleXMLElement into a DOMElement.

<?php
$xml = simplexml_load_file('example.xml');

$toDelete = array();

foreach ($xml->item as $item) {

    $price  = $item->Price1;

    if ($price < 50 ) { 
        $toDelete[] = $item;
    } 
}

foreach ($toDelete as $item) {
    $dom = dom_import_simplexml($item);
    $dom->parentNode->removeChild($dom);
}

echo $xml->asXML("result.xml");

output (live here)

<?xml version="1.0"?>
<all>
 <item>
  <ProductID>46121</ProductID> 
  <Price1>50</Price1> 
  </item>
</all>
Simone Nigro
  • 4,717
  • 2
  • 37
  • 72
0

Combine xpath to select all wanted <item>s with unset to remove an <item> from your SimpleXml object:

$xml = simplexml_load_string($x); // assume XML in $x
$items = $xml->xpath("/all/item[Price1 < 50]");
foreach ($items as $i) unset($i[0]);

Check the result with

echo $xml->asXML();

Comments:

  • the xpath expression is straightforward, the [] enclose the condition. xpath will return an array of SimpleXml elements to $items.
  • to remove a node, I use the self-reference-technique as discussed many times on SO.

see it working: https://eval.in/481413

Community
  • 1
  • 1
michi
  • 6,565
  • 4
  • 33
  • 56