Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : DOM Functions : DOMNode->removeChild()

DOMNode->removeChild()

Removes child from list of children ()

Example 540. Removing a child

<?php

$doc
= new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// we retrieve the chapter and remove it from the book
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo
$doc->saveXML();
?>

The above example will output:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
         "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
<book id="listing">
<title>My lists</title>

</book>

Code Examples / Notes » dom_domnode_removechild

pedro

You may also use the hasChild function:
<?php
while($node->hasChildNodes()) {
 $node->removeChild($node->childNodes->item(0));
}
?>
When you remove a childNode, the next node becomes the first one!


blaine

This might be obvious, but might help someone as well...
If you simply have a node that you need to remove (perhaps from an xpath) and don't know the parent node offhand (the examples seem to assume you have the parent in a variable), then you can do something easy like this...
$node->parentNode->removeChild($node);
parentNode is a scalar property of the Element.
Hope that helps.
--
Blaine Garrett
Executive Director of the Art Attack
http://theartattack.org


lsoethout

The previous example is not correct; it only works when the tags are direct childs of the top-level node.
Better is:
while($elem = $dom->getElementsByTagName("name")->item(0)) {
  $elem->parentNode->removeChild($elem);
}


sbeam

remove all children of a given node:
       
while ($parent->childNodes->length) {
     $parent->removeChild($parent->childNodes->item(0));
}


dave

remove all children of a given node (simple way):
$node->nodeValue = '';


23-feb-2007 08:05

If you want to remove all nodes of a given type, this might be an idea:
while($elem = $dom->getElementsByTagName("name")->item(0)) {
   $dom->removeChild($elem);
}
probably not the most efficient way, but it works


vsematika

For those who don't understand >sbeam at onsetcorps dot net on 02-Feb-2005 12:07< 'hack', here's a little discussion:
First but *wrong* try would be:
<?php
foreach ($parent->childNodes as $child) {
  $parent->removeChild($child);
?>
This doesn't work because DOM tree id modified on-the-fly and this confuses foreach loop.
The idea behind sbeam's trick is that after removing the first item in the first iteration, the second item in childNodes nodelist immediately becomes the first item. That's why we must _always_ remove the first child. Here's another implementation:
<?php
$count = $parent->childNodes->length;
for ($i = 0; $i < $count; $i++) {
  $oldNode = $parent->removeChild($parent->childNodes->item(0)); // !!! not item($i) !!!
}
?>


lusever

Delete with node:
<?php
$node->parentNode->removeChild($node);
?>


karan

can we directly remove a node which has some children or do we need to remove the children first.
while($mytn->hasChildNodes())
{
$mytn->removeChild($mytn->childNodes->item(0));
}
echo $j;//this shows correct no of children
echo $mytn->childNodes->length;//after removing it
                                        // shows 0..correct

$dom->save(net.xml);
but the changes r not reflected in the xml file


mytto

Back again on removing childs and iterators robustness.
Things get a bit more complicated when you only want to remove 'some' nodes according to a certain condition. Then you can't just remove the first one repeatedly.
The trick is to copy the content of the node list into a more robust collection than DOMNodeList, I name array!
The following piece of code will, for instance, remove all empty child nodes:
<?php
// Copy childNodes array
$childNodes = array();
foreach($node->childNodes as $childNode) {
 $childNodes[] = $childNode;
}
// Browse with the copy    
foreach ($childNodes as $childNode) {
 if (!$childNode->hasChildNodes()); {
   $childNode->parentNode->removeChild($childNode);
 }
}
?>


vasil rangelov

At the time of writing, I suppose rightfully, removeChild() removes only the selected node, but when you remove an element, it's child elements are not removed. If you want to achieve that, replaceChild() is the solution.
The following should remove all descendants of the $node DOMNode, regardless of it's name:
<?php
$node->replaceChild(new DOMElement($node->nodeName), $node);
?>
If you're replacing the root element, you must explicitly state that with $node->documentElement as the second argument.


Change Language


Follow Navioo On Twitter
DOMAttr->__construct()
DOMAttr->isId()
DOMCharacterData->appendData()
DOMCharacterData->deleteData()
DOMCharacterData->insertData()
DOMCharacterData->replaceData()
DOMCharacterData->substringData()
DOMComment->__construct()
DOMDocument->__construct()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()
DOMDocument->getElementById()
DOMDocument->getElementsByTagName()
DOMDocument->getElementsByTagNameNS()
DOMDocument->importNode()
DOMDocument->load()
DOMDocument->loadHTML()
DOMDocument->loadHTMLFile()
DOMDocument->loadXML()
DOMDocument->normalizeDocument()
DOMDocument->registerNodeClass()
DOMDocument->relaxNGValidate()
DOMDocument->relaxNGValidateSource()
DOMDocument->save()
DOMDocument->saveHTML()
DOMDocument->saveHTMLFile()
DOMDocument->saveXML()
DOMDocument->schemaValidate()
DOMDocument->schemaValidateSource()
DOMDocument->validate()
DOMDocument->xinclude()
DOMDocumentFragment->appendXML()
DOMElement->__construct()
DOMElement->getAttribute()
DOMElement->getAttributeNode()
DOMElement->getAttributeNodeNS()
DOMElement->getAttributeNS()
DOMElement->getElementsByTagName()
DOMElement->getElementsByTagNameNS()
DOMElement->hasAttribute()
DOMElement->hasAttributeNS()
DOMElement->removeAttribute()
DOMElement->removeAttributeNode()
DOMElement->removeAttributeNS()
DOMElement->setAttribute()
DOMElement->setAttributeNode()
DOMElement->setAttributeNodeNS()
DOMElement->setAttributeNS()
DOMElement->setIdAttribute()
DOMElement->setIdAttributeNode()
DOMElement->setIdAttributeNS()
DOMEntityReference->__construct()
DOMImplementation->__construct()
DOMImplementation->createDocument()
DOMImplementation->createDocumentType()
DOMImplementation->hasFeature()
DOMNamedNodeMap->getNamedItem()
DOMNamedNodeMap->getNamedItemNS()
DOMNamedNodeMap->item()
DOMNode->appendChild()
DOMNode->cloneNode()
DOMNode->hasAttributes()
DOMNode->hasChildNodes()
DOMNode->insertBefore()
DOMNode->isDefaultNamespace()
DOMNode->isSameNode()
DOMNode->isSupported()
DOMNode->lookupNamespaceURI()
DOMNode->lookupPrefix()
DOMNode->normalize()
DOMNode->removeChild()
DOMNode->replaceChild()
DOMNodelist->item()
DOMProcessingInstruction->__construct()
DOMText->__construct()
DOMText->isWhitespaceInElementContent()
DOMText->splitText()
DOMXPath->__construct()
DOMXPath->evaluate()
DOMXPath->query()
DOMXPath->registerNamespace()
dom_import_simplexml
eXTReMe Tracker