gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:40:15 24 4
gpt4 key购买 nike

我只是想问一下如何使用 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");

关于php - 通过 PHP 在 XML 文件中添加新节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15201433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com