2013-03-04 104 views
3

我只是想問一個問題。我如何在使用php的xml中插入新節點。我的XML文件(questions.xml)在下面給出通過PHP在XML文件中添加新節點

<?xml version="1.0" encoding="UTF-8"?> 
<Quiz> 
    <topic text="Preparation for Exam"> 
     <subtopic text="Science" /> 
     <subtopic text="Maths" /> 
     <subtopic text="english" /> 
    </topic> 
</Quiz> 

我想添加一個新的「subtext」和「text」屬性,即「g​​eography」。我如何使用PHP來做到這一點?預先感謝,但。 以及我的代碼是

<?php 

$xmldoc = new DOMDocument(); 
$xmldoc->load('questions.xml'); 



$root = $xmldoc->firstChild; 

$newElement = $xmldoc->createElement('subtopic'); 
$root->appendChild($newElement); 

// $ newText = $ xmldoc->一個createTextNode( '地質'); // $ newElement-> appendChild($ newText);

$xmldoc->save('questions.xml'); 

?>

+0

y這是我..沒有滿意的答覆。 。 – user2083529 2013-03-04 12:29:13

+0

因爲你沒有想到的解釋,但你可以使用一段代碼。沒有理由再次提出同樣的問題。 – 2013-03-04 12:30:39

+0

有一個原因..看到..我有一個有效的答覆後,再次發佈...所以有一個原因再次發佈。 – user2083529 2013-03-04 12:48:47

回答

7

我想用SimpleXML這個。它看起來有點像這樣:

// Open and parse the XML file 
$xml = simplexml_load_file("questions.xml"); 
// Create a child in the first topic node 
$child = $xml->topic[0]->addChild("subtopic"); 
// Add the text attribute 
$child->addAttribute("text", "geography"); 

你可以用echo顯示新的XML代碼或將它存儲在一個文件中。

// Display the new XML code 
echo $xml->asXML(); 
// Store new XML code in questions.xml 
$xml->asXML("questions.xml"); 
+1

謝謝..現在,這是一個令人滿意和非常好的答覆。 。我很欣賞你的努力 – user2083529 2013-03-04 12:39:18

3

最好最安全的方法是將XML文檔加載到一個PHP DOMDocument對象,然後去到你想要的節點,加上一個孩子,好不容易攢的新版本XML轉換成文件。

看看文檔:DOMDocument

的代碼示例:

// open and load a XML file 
$dom = new DomDocument(); 
$dom->load('your_file.xml'); 

// Apply some modification 
$specificNode = $dom->getElementsByTagName('node_to_catch'); 
$newSubTopic = $xmldoc->createElement('subtopic'); 
$newSubTopicText = $xmldoc->createTextNode('geography'); 
$newSubTopic->appendChild($newSubTopicText); 
$specificNode->appendChild($newSubTopic); 

// Save the new version of the file 
$dom->save('your_file_v2.xml'); 
+0

好的...我編輯了文件...我的編碼在那裏..但是我的代碼在最後添加了新的子標題...並且不添加文本屬性:( – user2083529 2013-03-04 12:27:38

+0

您必須創建一個新元素'$ newSubTopic = $ xmldoc-> createElement('subtopic');',然後創建一個新的文本節點'$ subTopicContent = $ xmldoc-> createTextNode('geology');',最後將textnode附加到新的主題元素,然後添加新的話題元素到你的願望節點。 – MatRt 2013-03-04 12:30:49

+0

啊所以..。它的工作..感謝人..我真的很感謝你的幫助 – user2083529 2013-03-04 12:33:48

-1

您可以使用PHP的Simple XML.你要讀取文件內容,用簡單的XML添加節點和寫的內容背部。

+0

是啊...你可以幫我這個...只是一個提示...我知道如何閱讀使用simplexml的東西,但不知道如何添加一個新的節點使用簡單的XML .. – user2083529 2013-03-04 12:25:59

+0

看到這個http ://www.php.net/manual/en/simplexmlelement.addchild.php – 2013-03-04 12:27:07