use*_*529 5 php xml simplexml xml-parsing
我只是想问一个问题..如何使用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>
Run Code Online (Sandbox Code Playgroud)
我想添加一个带有"text"属性的新"subtopic",即"geography".我怎么能用PHP做到这一点?提前谢谢.我的代码是
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('questions.xml');
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createElement('subtopic');
$root->appendChild($newElement);
Run Code Online (Sandbox Code Playgroud)
// $ newText = $ xmldoc-> createTextNode('geology'); // $ newElement-> appendChild($ newText);
$xmldoc->save('questions.xml');
Run Code Online (Sandbox Code Playgroud)
?>
我会使用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");
Run Code Online (Sandbox Code Playgroud)
您可以使用echo显示新的XML代码,也可以将其存储在文件中.
// Display the new XML code
echo $xml->asXML();
// Store new XML code in questions.xml
$xml->asXML("questions.xml");
Run Code Online (Sandbox Code Playgroud)
最好和安全的方法是将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');
Run Code Online (Sandbox Code Playgroud)