繁体   English   中英

使用php和dom处理xml文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM