0

Following from this: Appending data to XML file

I would instead like to prepend my new <thumbnail> element

I have this:

$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml');



$thumbnail = $xmldoc->createElement('thumbnail');
$thumbnail->setAttribute('preview', 'This is a preview');
$thumbnail->setAttribute('previewURL', 'This is a URL');
$thumbnail->setAttribute('thumb', 'This is a Thumb');

$title = $xmldoc->createElement('title');
$title->appendChild($xmldoc->createCDATASection('This is Title'));
$thumbnail->appendChild($title);


$description = $xmldoc->createElement('description');
$description->appendChild($xmldoc->createCDATASection('This is Description'));
$thumbnail->appendChild($description);


$xmldoc->getElementsByTagName('thumbnails')->item(0)->appendChild($thumbnail);
$xmldoc->save('sample.xml');

Which is working just fine, but it is appending the <thumbnail> to the bottom before </thumbnails> </mainXML>

I would now instead like it to prepend it after the <thumbnails> open.

The current XML is here: http://pastebin.com/4pWnFVfq

As you can see it appends in the bottom like i described.

How can i do this?

Community
  • 1
  • 1
Karem
  • 17,615
  • 72
  • 178
  • 278
  • [This question](http://stackoverflow.com/questions/2092012/simplexml-how-to-prepend-a-child-in-a-node) might be able to help you out. – Xavier Holt Oct 05 '11 at 19:21
  • @XavierHolt that was a good link. How can I out from that function make it work to my code ?? Please reply – Karem Oct 05 '11 at 20:37
  • It's the [insertBefore](http://php.net/manual/en/domnode.insertbefore.php) function that does the work. You should double-check the docs (linked), and Sean's answer - it looks like it works to me... – Xavier Holt Oct 05 '11 at 21:24

1 Answers1

1

The following should do what you're looking for.

<?php

$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml');



$thumbnail = $xmldoc->createElement('thumbnail');
$thumbnail->setAttribute('preview', 'This is a preview');
$thumbnail->setAttribute('previewURL', 'This is a URL');
$thumbnail->setAttribute('thumb', 'This is a Thumb');

$title = $xmldoc->createElement('title');
$title->appendChild($xmldoc->createCDATASection('This is Title'));
$thumbnail->appendChild($title);


$description = $xmldoc->createElement('description');
$description->appendChild($xmldoc->createCDATASection('This is Description'));
$thumbnail->appendChild($description);
$thumbs = $xmldoc->getElementsByTagName('thumbnails')->item(0);
$first_thumb = $thumbs->getElementsByTagName('thumbnail')->item(0);

$thumbs->insertbefore($thumbnail, $first_thumb);

$xmldoc->save('sample.xml');
?>
Sean McCully
  • 1,122
  • 3
  • 12
  • 21