note 50500 modified in function.dom-domnode-replacechild by didou
| From: | didou@php.net | Date: | Sat, 02 Apr 2005 22:46:47 +0000 |
| Subject: | note 50500 modified in function.dom-domnode-replacechild by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-87378@lists.php.net to get a copy of this message | ||
If you are trying to replace more than one node at once, you have to be careful about iterating over
the DOMNodeList. If the old node has a different name from the new node, it will be removed from
the list once it has been replaced. Use a regressive loop:
<?php
$xml = new DOMDocument;
$xml->load('docfile.xml');
$elements = $xml->getElementsByTagNameNS('http://www.example.com/NS/', '*');
$i = $elements->length - 1;
while ($i > -1) {
$element = $elements->item($i);
$ignore = false;
$newelement = $xml>createTextNode('Some new node!');
$element->parentNode->replaceChild($newelement, $element);
$i--;
}
?>
The loop counter ($i) will always be in the list's interval as removed elements indexes are
above the counter.
--was--
About the problem of replacing more than one child, there is an easier solution than what <roland
dot swingler at transversal dot com> proposed. Instead of a normal iteration, just use a
regressive loop.
<?php
$xml = new DOMDocument;
$xml->load('docfile.xml');
$elements = $xml->getElementsByTagNameNS('http://www.example.com/NS/', '*');
$i = $elements->length - 1;
while ($i > -1) {
$element = $elements->item($i);
$ignore = false;
$newelement = $xml>createTextNode('Some new node!');
$element->parentNode->replaceChild($newelement, $element);
$i--;
}
?>
The loop counter ($i) will always be in the list's interval as removed elements indexes are
above the counter.
http://php.net/manual/en/function.dom-domnode-replacechild.php