note 70177 added to function.dom-domdocument-importnode

From: Date: Thu, 05 Oct 2006 20:08:52 +0000
Subject: note 70177 added to function.dom-domdocument-importnode
Groups: php.notes 
Request: Send a blank email to php-notes+get-118098@lists.php.net to get a copy of this message
Editing XML with PHP can be a pain in the Secretary of State Powell, so here's a script to replace an XML node with a user-provided one through the POST. It's usually a good idea to run the $_POST['xml'] through a validation check and clean it for other thing before running this. Pretty much this script expects a user-provided node called $_POST['xml'] and the XPath of the node in the original document that you want to replace called $_POST['XPath']. It also loads the original XML document from $xml. The function nodeRunner begins with the root node of the document you're editting and the XPath for the root element (these are more to make recursion easy than anything else). $doc = new DOMDocument(); $doc->loadXML($xml); // $xml expects an XML string function nodeRunner ($node,$xpath) { global $doc; if ($xpath == $_POST['XPath']) { $xmlPost = new DOMDocument(); $xmlPost->loadXML($_POST['xml']); $newNode = $doc->importNode($xmlPost->firstChild,true); $node->parentNode->replaceChild($newNode,$node); } else { $page = 1; $section = 1; if ($node->hasChildNodes()) { foreach ($node->childNodes as $nodling) { $nodeName = $nodling->nodeName; if ($nodeName == 'page' || $nodeName == 'section') { nodeRunner ($nodling,$xpath."/".$nodeName."[".$$nodeName."]"); $$nodeName++; } } } } } nodeRunner ($doc->documentElement,"/root[1]"); // /root should be explicit name of the root element of the XPath $doc->saveXML(); ---- Server IP: 66.163.161.117 Probable Submitter: 129.79.86.3 ---- Manual Page -- http://www.php.net/manual/en/function.dom-domdocument-importnode.php Edit -- https://master.php.net/note/edit/70177 Del: integrated -- https://master.php.net/note/delete/70177/integrated Del: useless -- https://master.php.net/note/delete/70177/useless Del: bad code -- https://master.php.net/note/delete/70177/bad+code Del: spam -- https://master.php.net/note/delete/70177/spam Del: non-english -- https://master.php.net/note/delete/70177/non-english Del: in docs -- https://master.php.net/note/delete/70177/in+docs Del: other reasons-- https://master.php.net/note/delete/70177 Reject -- https://master.php.net/note/reject/70177 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#118098) next »