I tried to insert new data into an existing XML file, but it does not work. Here is my xml file:
<list> <activity>swimming</activity> <activity>running</activity> <list>
Now my idea was to create two files: an index page, where it displays what is in the file, and provides a field for inserting new elements, and also a php page that will insert data into the XML file. Here's the index.php code:
<html> <head><title>test</title></head> </head> <?php $xmldoc = new DOMDocument(); $xmldoc->load('sample.xml', LIBXML_NOBLANKS); $activities = = $xmldoc->firstChild->firstChild; if($activities!=null){ while(activities!=null){ echo $activities->textContent.'<br/>'; activities = activities->nextSibling. } } ?> <form name='input' action='insert.php' method='post'> insert activity: <input type='text' name='activity'/> <input type='submit' value='send'/> </form> </body> </html
and here is the code for insert.php:
<?php header('Location:index.php'); $xmldoc = new DOMDocument(); $xmldoc->load('sample.xml'); $newAct = $_POST['activity']; $root = $xmldoc->firstChild; $newElement = $xmldoc->createElement('activity'); $root->appendChild($newElement); $newText = $xmldoc->createTextNode($newAct); $newElement->appendChild($newText); $xmldoc->save('sample.xml'); ?>
The user should access index.php, where he will see a list of the current actions present in the XML file, and the text box below where he can insert new actions. After clicking the submit button, the page will call insert.php, which contains the code that opens the XML file in the DOM tree, inserts a new node under the root of the node and calls the index.php page, where the user should be able to see a list of activities, his new activity there under by others. This does not work. When I press the button to send a new record, the pages are updated and apparently nothing is happening, the XML is the same as before. What have I done wrong? Also, I would like to know if there is a better way to do this.
dom xml php
David McDavidson
source share