2011-01-23 20 views
0

我一直在瀏覽幾個小時,並且沒有簡單的解釋或演示如何將新的子元素插入到XML文件中,然後保存XML文件。需要協助,使用PHP插入新的子元素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文件)

回答

1

有PHP的手動其爲您提供所需所有信息內的示例:從

  • 上一層>負載()
    //負載的xml: http://php.net/manual/en/domdocument.save.php

    需要的方法文件

  • 上一層>的createElement()
    //創建一個元件節點
  • 上一層>一個createTextNode()
    //創建一個textNode
  • れ>的appendChild()
    //將一個節點追加到另一個節點
  • DOMDocument-> save()
    //將XML保存到文件中

<?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'); 
?> 
+0

是的,我訪問過的鏈接和例子搞糊塗了一點。所以基本上..打開xml文件,使路徑在父節點內創建一個新元素,然後在該新元素中的兩個其他節點以及帶有它們的值的文本節點,然後將該整個新元素附加到根? (將新節點附加到父節點)? – Vaughn

+0

我在我的答案中列出了一個工作示例。有一個更簡單的方法使用片段(但這不是一個官方的DOM標準,在我心中有點髒):http://de.php.net/manual/en/domdocumentfragment.appendxml.php –

+0

完美的作品現在感謝莫爾博士。我所需要的只是一個更清晰的例子,所以我可以知道這個的基本結構。 – Vaughn