-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
  • 193,403
  • 52
  • 435
  • 836
tree em
  • 20,379
  • 30
  • 92
  • 130
  • 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. – tree em 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? – tree em Dec 31 '10 at 16:12

1 Answers1

1
foreach ($xpath->query('//junk') as $elem)
ajreal
  • 46,720
  • 11
  • 89
  • 119