note 45967 deleted from function.dom-domdocument-importnode by didou
| From: | didou@php.net | Date: | Fri, 17 Dec 2004 17:40:58 +0000 |
| Subject: | note 45967 deleted from function.dom-domdocument-importnode by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-81927@lists.php.net to get a copy of this message | ||
Note Submitter: jon at codessence dot net
----
Here is a little tip that may help some of you out.
To import an entire node including its descendants the second argument of importNode needs to be set
to TRUE.
Example: Lets say you want to add a paragraph node to your XML, but you have anchor tags embedded in
the text of the paragraph you want to add. How can you get that node with its anchor tags as
descendants into your XML. Simple...
<?php
// your xml
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<page>
<paragraph>blah blah blah blah</paragraph>
</page>';
$doc = new DOMDocument;
$doc->loadXML($xml); // load your xml file
// your paragraph in well formed xhtml with links
$xhtml = 'Hello <a href="http://www.google.com">World</a>!';
// put your paragraph into a string of xml like so...
$new_xml = '<?xml version="1.0" encoding="UTF-8"?>
<paragraph>'.$xhtml.'</paragraph>';
// create a new DOMDocument and load in your new paragraph
$import_dom = new DOMDocument;
$import_dom->loadXML($new_xml);
// do an xpath query to get back your node
$xpath = new domXPath($import_dom);
$xpathQuery = $xpath->query("/paragraph");
foreach($xpathQuery as $node) {
// use cloneNode with TRUE to copy all descendants of a node
$import_node = $node->cloneNode(true);
}
// use importNode with 2nd arg TRUE to import all descendants of a node
$paragraph = $doc->importNode($import_node, true);
// append the new node to the root node (documentElement)
$paragraph = $doc->documentElement->appendChild($paragraph);
// save your new XML
$xml = $doc->saveXML();
echo $xml;
?>
Hope this saves you some hours of frustration.
Jon