6

我只是想问一个问题..如何使用 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');

?>

4

3 回答 3

10

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

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");
于 2013-03-04T12:32:17.523 回答
5

最好且安全的方法是将您的 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');
于 2013-03-04T12:22:21.187 回答
-1

You can use PHP's Simple XML. You have to read the file content, add the node with Simple XML and write the content back.

于 2013-03-04T12:23:01.033 回答