ronyan
ronyan

Reputation: 23

Modify existing XML file with DomDocument PHP

I have an existing xml file of the following format:

<root>

<word>
<label></label>
<definition></definition>
</word>
...

</root>

I'm taking in text through input boxes for the word and definition on the page and passing it to the php script via GET. The goal for the php script is to take the user input and add an additional word element containing the nested elements label (contains actual word) and definition (contains word definition) to the XML document vocab.xml.

Here is the script:

<?php
$word = $_GET['word'];
$definition = $_GET['definition'];

$dom = new DomDocument();
$dom->load("vocab.xml");

$root = $dom->documentElement;

$node = $dom->createElement("word");

$node2 = $dom->createElement("label", $word);
$node3 = $dom->createElement("definition", $definition);

$node->appendChild($node2);
$node->appendChild($node3);
$root->appendChild($node);

$dom->asXML("vocab.xml");
?>

As it stands now the script appears to execute correctly but checking the XML file reveals that no changes were made.

Upvotes: 0

Views: 2039

Answers (1)

hek2mgl
hek2mgl

Reputation: 157927

DOMDocument has no method asXML(). You need to use save():

$dom->save("vocab.xml");

Upvotes: 1

Related Questions