0

I want to use the dom removeChild function in php to remove everything between a tag.

my xml looks like

<root>
  <element>text</element>

  <remove>
    text
    <morexml>text</morexml>
  </remove>
</root>

Now I want to remove the tag including its entire inside. How do I do this? I do not have a clue. I am trying to use the only dom function i found: removeChild.

When removed it has to look like this:

 <root>
      <element>text</element>

 </root>

Is there a php dom function to do this? I can not find it on google or stackoverflow.

botenvouwer
  • 4,334
  • 9
  • 46
  • 75
  • http://stackoverflow.com/questions/1153697/php-delete-xml-element – jcho360 Oct 09 '12 at 13:12
  • You can try to do it with regex. following link might help you: http://stackoverflow.com/questions/226562/how-can-i-remove-an-entire-html-tag-and-its-contents-by-its-class-using-a-rege – kjurkovic Oct 09 '12 at 13:29

2 Answers2

2
$dom = new DOMDocument;
$dom->loadXML($xml);
$dom->getElementsByTagName('root')->item(0)
   ->removeChild($dom->getElementsByTagName('remove')->item(0));

This is very specific, though. You can use XPath if you need more generality:

foreach ($xpath->query('//remove') as $node) {
   $node->parentNode->removeChild($node);
}
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
1

You can use XPath and delete over XPath the node.

Use DOM and XPath to remove a node from a sitemap file

PHP SimpleXML - Remove xpath node

here on Stackoverflow are a lot of posts. Perhaps you should search here at first.

Community
  • 1
  • 1
René Höhle
  • 26,716
  • 22
  • 73
  • 82