note 85813 added to class.domnodelist

From: Date: Thu, 18 Sep 2008 22:44:40 +0000
Subject: note 85813 added to class.domnodelist
Groups: php.notes 
Request: Send a blank email to php-notes+get-144527@lists.php.net to get a copy of this message
Get some nodes from an existing xml file and add them to a new file: <?php $dom = new DOMDocument; $dom->load($xmlsource); /*create the xPath object _after_ loading the xml source, otherwise the query won't work:*/ $xPath = new DOMXPath($dom); /*now get the nodes in a DOMNodeList:*/ $nodeList = $xPath->query($anXPathExpr); /*create a new DOMDocument and add a root element:*/ $newDom = new DOMDocument('1.0','UTF-8'); $root = $newDom->createElement('root'); $root = $newDom->appendChild($root); /* append all nodes from $nodeList to the new dom, as children of $root:*/ foreach ($nodeList as $domElement){ $domNode = $newDom->importNode($domElement, true); $root->appendChild($domNode); } /*please note: importNode does not cast a DOMElement to a DOMNode!*/ /*save the new dom */ echo 'Wrote: ' . $newDom->save('newDOM.xml') . ' bytes'; ?> the following won't work and you'll end up with a DOMException: 'Wrong Document Error' (at least I did): <?php foreach ($nodeList as $element){ $root->appendChild($element); } ?> Cheers! ;-) --- WindowsXP, WAMP5 (appache 2.2.6), PHP 5.2.5, DOM/XML API Version 20031129, libxml 2.6.26 --- ---- Server IP: 212.124.37.9 Probable Submitter: 91.32.173.105 ---- Manual Page -- http://www.php.net/manual/en/class.domnodelist.php Edit -- https://master.php.net/note/edit/85813 Del: integrated -- https://master.php.net/note/delete/85813/integrated Del: useless -- https://master.php.net/note/delete/85813/useless Del: bad code -- https://master.php.net/note/delete/85813/bad+code Del: spam -- https://master.php.net/note/delete/85813/spam Del: non-english -- https://master.php.net/note/delete/85813/non-english Del: in docs -- https://master.php.net/note/delete/85813/in+docs Del: other reasons-- https://master.php.net/note/delete/85813 Reject -- https://master.php.net/note/reject/85813 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#144527) next »