note 48485 added to function.dom-domnode-replacechild
| From: | aidan@php.net | Date: | Sun, 26 Dec 2004 10:17:37 +0000 |
| Subject: | note 48485 added to function.dom-domnode-replacechild | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-82307@lists.php.net to get a copy of this message | ||
Here is a simple example for replacing a node:
Let's define our XML like so:
<?php
$xml = <<<XML
<?xml version="1.0"?>
<root>
<parent>
<child>bar</child>
<child>foo</child>
</parent>
</root>
XML;
?>
If we wanted to replace the entire <parent> node, we could do something like this:
<?php
// Create a new document fragment to hold the new <parent> node
$parent = new DomDocument;
$parent_node = $parent ->createElement('parent');
// Add some children
$parent_node->appendChild($parent->createElement('child', 'somevalue'));
$parent_node->appendChild($parent->createElement('child',
'anothervalue'));
// Add the keywordset into the new document
// The $parent variable now holds the new node as a document fragment
$parent->appendChild($parent_node);
?>
Next, we need to locate the old node:
<?php
// Load the XML
$dom = new DomDocument;
$dom->loadXML($xml);
// Locate the old parent node
$xpath = new DOMXpath($dom);
$nodelist = $xpath->query('/root/parent');
$oldnode = $nodelist->item(0);
?>
We then import and replace the new node:
<?php
// Load the $parent document fragment into the current document
$newnode = $dom->importNode($parent->documentElement, true);
// Replace
$oldnode->parentNode->replaceChild($newnode, $oldnode);
// Display
echo $dom->saveXML();
?>
Our new node is successfully imported:
<?xml version="1.0"?>
<root>
<parent><child>somevalue</child><child>anothervalue</child></parent>
</root>
----
Manual Page -- http://www.php.net/manual/en/function.dom-domnode-replacechild.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+48485
Delete -- http://master.php.net/manage/user-notes.php?action=delete+48485&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48485&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48485&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48485&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48485&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48485&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+48485&report=yes
Search -- http://master.php.net/manage/user-notes.php