-1

Removed ALL junk nodes in xml using php

This is the sample input for the example:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <!--comment1-->
    <elem>a</elem>
    <junk>b</junk>
    <elem>
        <!--comment2-->
        <junk>c<junk>d</junk></junk>
    </elem>
    <!--comment3-->
    <junk>e</junk>
</root>

This is the resulting XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>

    <elem>a</elem>

    <elem>


    </elem>


</root>

I look documents and applied like this:

$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);

foreach ($xpath->query('/root/') as $elem) {
    $elem->parentNode->removeChild($elem);
}

for my case will remove all node "junk" and they will everywhere in xml document.

hakre
  • 184,866
  • 48
  • 414
  • 792
kn3l
  • 18,459
  • 28
  • 85
  • 123
  • possible duplicate of [PHP - Delete XML Element](http://stackoverflow.com/questions/1153697/php-delete-xml-element) – Pekka Dec 31 '10 at 15:42
  • More convenient solution using XPath here: http://stackoverflow.com/questions/2499694/delete-elements-in-xml – Pekka Dec 31 '10 at 15:42
  • yes,but for me ,they are everywhere. i want to delete ALL elements that. – kn3l Dec 31 '10 at 16:04
  • @python the accepted answer in my second link should work for you. Something like `$entity->deleteNodes('//entity[type="junk"]');` – Pekka Dec 31 '10 at 16:09
  • yes,but it used thid-parties,are there any where? – kn3l Dec 31 '10 at 16:12

1 Answers1

1
foreach ($xpath->query('//junk') as $elem)
ajreal
  • 45,869
  • 10
  • 83
  • 118