leon_nerd Posted June 16, 2010 Share Posted June 16, 2010 Hi Guys, I want to insert a node with children at a specific location in the XML file. How do I do it? For eg. If I have an XML like: <myvalues> <image name="img01"> <src>test</src> </image> <image name="img02"> <src>test</src> </image> <image name="img03"> <src>test</src> </image> </myvalues> I want to insert: <image name="img11"> <src>test</src> </image> between <image name="img01"> & <image name="img02">. How do I do this? I am using SimpleXML right now to read the XML. Thanks. Link to comment https://forums.phpfreaks.com/topic/204944-inserting-a-xml-node-at-a-specific-location/ Share on other sites More sharing options...
ignace Posted June 16, 2010 Share Posted June 16, 2010 $element = $doc->createElement( 'image' )->appendChild( $doc->createElement( 'src', 'test' ) ); $element->setAttribute( 'name' , 'img11' ); $doc->insertBefore($element, $xpath->query( '//[@name=img02]' )->item( 0 )); Link to comment https://forums.phpfreaks.com/topic/204944-inserting-a-xml-node-at-a-specific-location/#findComment-1073036 Share on other sites More sharing options...
leon_nerd Posted June 16, 2010 Author Share Posted June 16, 2010 Thanks. I tried this code but it is inserting the new node at the end of the XML file, outside the XML structure. I am using the following code: $xml = new DomDocument(); $xml->preserveWhitespace = false; $xml->load('myXMLFile.xml'); $newNode = $xml->createElement('tryimage'); $xpath = new DOMXpath($xml); $elements = $xpath->query('/myvalues/image[name="img01"]'); $refNode = $elements->item(0); $xml->insertBefore($newNode, $refNode->nextSibling); header('Content-Type: text/plain'); echo $xml->saveXML(); and the output is: <xml....> <myvalues> <image name="01"> </image> . . . </myvalues> <tryimage /> Link to comment https://forums.phpfreaks.com/topic/204944-inserting-a-xml-node-at-a-specific-location/#findComment-1073064 Share on other sites More sharing options...
katierosy Posted June 18, 2010 Share Posted June 18, 2010 The link below may help http://forums.devshed.com/php-development-5/insert-update-delete-in-xml-file-using-php-699891.html Link to comment https://forums.phpfreaks.com/topic/204944-inserting-a-xml-node-at-a-specific-location/#findComment-1074088 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.