note 45073 added to function.simplexml-import-dom
| From: | MichaelDouma at osu1 dot php dot net | Date: | Wed, 25 Aug 2004 04:01:30 +0000 |
| Subject: | note 45073 added to function.simplexml-import-dom | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-75241@lists.php.net to get a copy of this message | ||
# Insert a node in your SimpleXML document at the location of an XPath
# (This will be obsolete if the functionality is added to SimpleXML, and there is NO error checking)
function insertAtXPath (&$inSXE, $xpathInsertNode, $newElementName, $newElementText) {
# convert $inSXE to the DOM model
$dom_sxe = dom_import_simplexml($inSXE);
# start a new element, and build onto it
$dom = new domdocument("1.0");
$newEl = $dom->createElement($newElementName);
$newElText = $dom->createTextNode($newElementText);
$newEl->appendChild($newElText);
# connect the new element to the $dom_sxe
$dom_sxe = $dom->importnode($dom_sxe, true);
$dom_sxe = $dom->appendchild($dom_sxe);
# find the place to append it with XPath
$xpath = new domXPath($dom);
$xpathQuery = $xpath->query($xpathInsertNode);
foreach ($xpathQuery as $node) { $node->insertBefore($newEl); }
# convert back to SimpleXML
$inSXE = simplexml_import_dom($dom);
}
# $xml is your SimpleXML object
$xml = simplexml_load_string($xmlstr);
# Specifics of the node you want to add
$xpathInsertNode = "/PAGE/ITEM[position()=3]";
$newElementName = "FOO";
$newElementText = "GOO";
# call the function
insertAtXPath($xml, $xpathInsertNode, $newElementName, $newElementText);
----
Manual Page -- http://www.php.net/manual/en/function.simplexml-import-dom.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+45073
Delete -- http://master.php.net/manage/user-notes.php?action=delete+45073&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+45073&report=yes
Search -- http://master.php.net/manage/user-notes.php