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: ht开发者_开发问答tp://pastebin.com/4pWnFVfq
As you can see it appends in the bottom like i described.
How can i do this?
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');
?>
精彩评论