我有如下的XML文件:操纵用PHP的XML文件和DOM
<?xml version="1.0" encoding="UTF-8"?>
<root version="8.0.0.0">
<songs name="Album">
<row>
<song artist="artist_name">Track1</song>
</row>
<row>
<song artist="artist_name">Track2</song>
</row>
<row>
<song artist="artist_name">Track3</song>
</row>
<row>
<song artist="artist_name">Track4</song>
</row>
</songs>
</root>
现在我想多带些行更新此文件。我如何将数据追加到现有行元素的顶部?同时添加新的元素,我想检查曲目 - Track1,Track2不重复。
我目前正在操纵该XML文件用PHP:DOM,但其在现有行的底部附加数据。用来做上面的东西
PHP代码
<?php
//Creates XML string and XML document using the DOM
$dom = new DOMDocument();
$dom->formatOutput = true;
$dom->Load('C:/wamp/www/xml/test1.xml');
$root = $dom->firstChild;
$list = $root->childNodes->item(1);
if(isset($_POST['submit'])){
$artistName = $_POST['name'];
$track = $_POST['track'];
$row = $dom->createElement('row');
$list->appendChild($row);
$song = $dom->createElement('song');
$row->appendChild($song);
$song->setAttribute('artist', $artistName);
$wcm_node = $dom->createTextNode($track);
$song->appendChild($wcm_node);
}
// Code to format XML after appending data
$outXML = $dom->saveXML(); // put string in outXML
//now create a brand new XML document
$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true; //yup, going to try to make this format again
//pass the output of the first bunch of stuff we did to the new XML document:
$xml->loadXML($outXML);
//now display the cleanly formatted output without using LIBXML_NOBLANKS (which may have undesired consequences
$xml->save('test1.xml'); // save as file
}
?>
请让我知道,我怎么能做到这一点。
感谢
请告诉我们一些PHP代码 – soju 2011-03-03 14:51:38
可能[PHP XML插入元素之后(或者是)的副本前)到另一个元件(http://stackoverflow.com/questions/4723747/php-xml-inserting-element-after-or-before-another-element) – Gordon 2011-03-03 15:10:37