Php – adding a new node in XML file via PHP


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"?>
   <topic text="Preparation for Exam">
      <subtopic text="Science" />
      <subtopic text="Maths" />
      <subtopic text="english" />

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


$xmldoc = new DOMDocument();

$root = $xmldoc->firstChild;

$newElement = $xmldoc->createElement('subtopic');

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



Best Solution

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