code
code

Reputation: 1081

Inserting a XML node at top

I'm trying to figure out how to get the xml node to insert (insertBefore) on top instead after. For example: image1, image2, image3.

   <data>
   <image src="image3" />  <-- Notice 
   <image src="image2" />  <-- Notice 
   <image src="image1" />
   </data>        



    $dom = new DOMDocument();
    $dom->formatOutput = true;

    $dom->load('myfile.xml');

    $root = $dom->documentElement;
    $newresult = $root->appendChild( $dom->createElement('image') );

    $newresult->setAttribute('id', '10');
    $newresult->setAttribute('src', pic.jpg');
    $newresult->setAttribute('desc', 'Timothy');

    //echo ''. $dom->saveXML() .'';
    $dom->save('myfile.xml') or die('XML Manipulate Error');

Thanks! I would greatly appreciate any help you can give me!

Upvotes: 0

Views: 204

Answers (1)

salathe
salathe

Reputation: 51950

Instead of appendChild(), you want to use insertBefore().

Replace

$newresult = $root->appendChild( $dom->createElement('image') );

With

$newresult = $root->insertBefore($dom->createElement('image'), $root->firstChild);

The changed code says to insert the new image element before the first child of the data element. This still works even if the data element has no child elements.

Here's a quick demo.

Upvotes: 2

Related Questions