[英]Manipulate xml file with php and dom
我有如下XML文件:
<?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不是重復的。
目前我正在用php:dom操作這個xml文件,但它在現有行的底部附加了數據。
用於執行上述操作的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
}
?>
請讓我知道,我怎么做。
謝謝
這不是追加,而是前期 。 DOM也有一種方法:
示例( 演示 ):
$dom = new DOMDocument;
$dom->loadXml('<rows><row xml:id="r1"/></rows>');
$dom->documentElement->insertBefore(
$dom->createElement('row', 'new row'),
$dom->getElementById('r1')
);
$dom->formatOutput = TRUE;
echo $dom->saveXml();
輸出:
<?xml version="1.0"?>
<rows>
<row>new row</row>
<row xml:id="r1"/>
</rows>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.