adding a new node in XML file via PHP

自作多情 提交于 2019-12-18 12:37:18

问题


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>

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

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

?>


回答1:


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



回答2:


The best and safe way is to load your XML document into a PHP DOMDocument object, and then go to your desired node, add a child, and finally save the new version of the XML into a file.

Take a look at the documentation : DOMDocument

Example of code:

// 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');



回答3:


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.



来源:https://stackoverflow.com/questions/15201433/adding-a-new-node-in-xml-file-via-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!