将数据预先添加到XML文件

时间:2011-10-05 19:17:49

标签: php xml

以下是: Appending data to XML file

我想改用我的新< thumbnail>元件

我有这个:

$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');

哪个工作正常,但在<thumbnail>

之前将</thumbnails> </mainXML>追加到底部

我现在更喜欢在&lt; thumbnails&gt;之后添加它。开。

当前的XML位于:http://pastebin.com/4pWnFVfq

正如你所看到的,它像我描述的那样贴在底部。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

以下内容应该可以满足您的需求。

<?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');
?>