我正在使用創建XML的簡單PHP腳本。PHP - 使用DOM編輯XML
XML的樣子:
<?xml version="1.0" encoding="UTF-8"?>
<article id="1"><published>05/01/2015 04:32:36</published><author position="writer">John Stewart</author>
沒有什麼特別的嗎?是的,之後我又編寫了另一個PHP腳本,試圖將第二篇文章添加到XML中。
代碼如下:
$dom=new DOMDocument();
$dom->load("articles.xml");
$article=$dom->createElement("article");
$article->setAttribute("id", 2);
$published=$dom->CreateElement("published");
$publishedDate=$dom->createTextNode(date("d/m/Y h:i:s", strtotime("tomorrow")));
$published->appendChild($publishedDate);
$article->appendChild($published);
$author=$dom->createElement("author");
$author->setAttribute("position", "writer");
$authorName=$dom->createTextNode("Ivan Dimov");
$author->appendChild($authorName);
$article->appendChild($author);
$dom->documentElement->appendChild($article);
$dom->save("articles.xml");
我可能是盲目的,因爲這個代碼看起來對我好,但生成XML看起來是這樣的:
<?xml version="1.0" encoding="UTF-8"?>
<article id="1"><published>05/01/2015 04:32:36</published><author position="writer">John Stewart</author>
<article id="2"><published>06/01/2015 12:00:00</published><author position="writer">Ivan Dimov</author></article></article>
所以一般情況下,增加了新的<article>
在結束之前,現在XML在結尾處有兩次結束文章標記。
有人可以幫助我找到正確的方法如何做到這一點?如果你找時間解釋我出了什麼問題,那就太棒了。
謝謝大家閱讀
注意你必須在年底'article'和'articleS'標籤。第二個有一個尾隨's'。 – fedorqui
真的好點@fedorqui,無論如何,現在我在編輯之前將其更改爲XML文件。但我仍然需要改變這種PHP編輯XML的方式,現在我有在最後兩次 – Andurit