user2329752
user2329752

Reputation: 77

Remove parent node in php

I want to remove all product with category=phones from my xml:

<SHOP>
  <ITEM>
    <CATEGORY>Computers</CATEGORY>
    <NAME>DELL</NAME>
  </ITEM>
  <ITEM>
    <CATEGORY>Computers</CATEGORY>
    <NAME>IBM</NAME>
  </ITEM>
  <ITEM>
    <CATEGORY>Phones</CATEGORY>
    <NAME>Apple</NAME>
  </ITEM>
</SHOP>

I tried this solutions:

$doc = new DomDocument();
$doc->load('product.xml');
$xpath = new DomXPath($doc);
$nodes = $xpath->query('ITEM/CATEGORY');

for ($i = 0; $i < $nodes->length; $i++) {     
    $node = $nodes->item($i);       
    if ($node->nodeValue == 'Phones') {
        $node->parentNode->removeChild($node);
    }         
}

But it delete only attribute CATEGORY but I need to delete all ITEM node with thit category. How should i change the code?

Upvotes: 1

Views: 2103

Answers (1)

Blue
Blue

Reputation: 22921

You were removing category from item. You want to remove item from shop (Both parents). Easiest way to do this:

$node->parentNode->parentNode->removeChild($node->parentNode);

See it in action at 3v4l here:

<?php

$xml_string = <<<EOT
<SHOP>
  <ITEM>
    <CATEGORY>Computers</CATEGORY>
    <NAME>DELL</NAME>
  </ITEM>
  <ITEM>
    <CATEGORY>Computers</CATEGORY>
    <NAME>IBM</NAME>
  </ITEM>
  <ITEM>
    <CATEGORY>Phones</CATEGORY>
    <NAME>Apple</NAME>
  </ITEM>
</SHOP>
EOT;

$doc = new DomDocument();
$doc->loadXML($xml_string);
$xpath = new DomXPath($doc);
$nodes = $xpath->query('ITEM/CATEGORY');

for ($i = 0; $i < $nodes->length; $i++) {     
    $node = $nodes->item($i);
    if ($node->nodeValue == 'Phones') {
        $node->parentNode->parentNode->removeChild($node->parentNode);
    }         
}

echo $doc->saveXML();

Upvotes: 3

Related Questions