我现在已经浏览了几个小时了,没有简单的解释或演示如何将新的子元素插入XML文件然后保存XML文件。
这是XML树..(非常简单)
< book >
<chapter>
<title>Everyday Italian</title>
<year>2005</year>
</chapter>
<chapter>
<title>Harry Potter</title>
<year>2005</year>
</chapter>
<chapter>
<title>XQuery Kick Start</title>
<year>2003</year>
</chapter>
< / book >
... 我非常感谢任何帮助。再次回顾一下,我有一个PHP文件,它的目标是插入一个新的“章节”,带有特定的“title”和“year”,然后保存新文件(基本上覆盖book.xml文件)
答案 0 :(得分:1)
php-manual中有一个例子,它为您提供所需的所有信息: http://php.net/manual/en/domdocument.save.php
您需要的方法:
,
<?php
//create a document
$doc=new DOMDocument;
//load the file
$doc->load('book.xml');
//create chapter-element
$chapter=$doc->createElement('chapter');
//create title-element
$title=$doc->createElement('title');
//insert text to the title
$title->appendChild($doc->createTextNode('new title for a new chapter'));
//create year-element
$year=$doc->createElement('year');
//insert text to the year
$year->appendChild($doc->createTextNode('new year for a new chapter'));
//append title and year to the chapter
$chapter->appendChild($title);
$chapter->appendChild($year);
//append the chapter to the root-element
$doc->documentElement->appendChild($chapter);
//save it into the file
$doc->save('book.xml');
?>