通过PHP在XML文件中添加新节点
我只是想问一个问题。我如何在使用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”属性,即“geography”。我如何使用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');
?>
我想用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");
谢谢..现在,这是一个令人满意和非常好的答复。 。我很欣赏你的努力 – user2083529 2013-03-04 12:39:18
最好最安全的方法是将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');
好的...我编辑了文件...我的编码在那里..但是我的代码在最后添加了新的子标题...并且不添加文本属性:( – user2083529 2013-03-04 12:27:38
您必须创建一个新元素'$ newSubTopic = $ xmldoc-> createElement('subtopic');',然后创建一个新的文本节点'$ subTopicContent = $ xmldoc-> createTextNode('geology');',最后将textnode附加到新的主题元素,然后添加新的话题元素到你的愿望节点。 – MatRt 2013-03-04 12:30:49
啊所以..。它的工作..感谢人..我真的很感谢你的帮助 – user2083529 2013-03-04 12:33:48
您可以使用PHP的Simple XML.你要读取文件内容,用简单的XML添加节点和写的内容背部。
是啊...你可以帮我这个...只是一个提示...我知道如何阅读使用simplexml的东西,但不知道如何添加一个新的节点使用简单的XML .. – user2083529 2013-03-04 12:25:59
看到这个http ://www.php.net/manual/en/simplexmlelement.addchild.php – 2013-03-04 12:27:07
y这是我..没有满意的答复。 。 – user2083529 2013-03-04 12:29:13
因为你没有想到的解释,但你可以使用一段代码。没有理由再次提出同样的问题。 – 2013-03-04 12:30:39
有一个原因..看到..我有一个有效的答复后,再次发布...所以有一个原因再次发布。 – user2083529 2013-03-04 12:48:47