通过PHP在XML文件中添加新节点

时间:2013-03-04 12:19:08

标签: php xml xml-parsing simplexml

我只是想问一个问题..如何使用php在xml中插入新节点。我的XML文件(questions.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>

我想添加一个带有“text”属性的新“subtopic”,即“geography”。我怎么能用PHP做到这一点?提前谢谢。 我的代码是

<?php

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



$root = $xmldoc->firstChild;

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

// $ newText = $ xmldoc-&gt; createTextNode('geology');    // $ newElement-&gt; appendChild($ newText);

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

&GT;

3 个答案:

答案 0 :(得分:9)

我会使用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 :(得分:4)

最好和安全的方法是将XML文档加载到PHP DOMDocument对象中,然后转到所需的节点,添加子节点,最后将新版本的XML保存到文件中。

查看文档:{​​{3}}

代码示例:

// 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');

答案 2 :(得分:-1)

您可以使用PHP的Simple XML.您必须阅读文件内容,使用Simple XML添加节点并重新编写内容。

相关问题