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


adding a new node in XML file via PHP

我只是想问如何使用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>

我想添加一个新的"子主题"。使用"文本"属性,即"地理"。我如何使用PHP做到这一点?不过还是先谢谢你。我的代码是

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

$root = $xmldoc->firstChild;
$newElement = $xmldoc->createElement('subtopic');
$root->appendChild($newElement);
// $newText = $xmldoc->createTextNode('geology');
// $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");

最好且安全的方法是将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');

您可以使用PHP的简单XML。您必须读取文件内容,用Simple XML添加节点,然后将内容写回来。