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

2022-01-10 00:00:00 xml xml-parsing php simplexml

我只是想问一个问题..如何使用 php 在 xml 中插入新节点.我的 XML 文件 (questions.xml) 在下面给出

I just wanted to ask a question .. how can i insert a new node in an xml using php. my XML file (questions.xml) is given below

<?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 做到这一点?不过提前谢谢.我的代码是

I want to add a new "subtopic" with "text" attribute, that is "geography". How can i do this using PHP? Thanks in advance though. well my code is

<?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);

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

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

?>

推荐答案

我会使用 SimpleXML 为此.它看起来像这样:

I'd use SimpleXML for this. It would look somehow like this:

// 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 代码,也可以将其存储在文件中.

You can either display the new XML code with echo or store it in a file.

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

相关文章