Php – Inserting data in XML file with PHP DOM


I was trying to insert new data into an existing XML file, but it's not working. Here's my xml file:


Now, my idea was making two files: an index page, where it displays what's on the file and provides a field for inserting new elements, and a php page which will insert the data into the XML file. Here's the code for index.php:


    $xmldoc = new DOMDocument();
    $xmldoc->load('sample.xml', LIBXML_NOBLANKS);

    $activities = = $xmldoc->firstChild->firstChild;
            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'/>

and here's the code for insert.php:

    $xmldoc = new DOMDocument();

    $newAct = $_POST['activity'];

    $root = $xmldoc->firstChild;

    $newElement = $xmldoc->createElement('activity');
    $newText = $xmldoc->createTextNode($newAct);


The user is to access index.php, where he would see a list of the current activities present in the XML file, and a text field below where he can insert new activities. Upon clicking the send button, the page would call insert.php, which contains a code that opens the XML file in a DOM tree, inserts a new node under the root node and calls back the index.php page, where the user should be able to see the list of activities, his new activity there under the others. It is not working. When i click on the button to submit a new entry, the pages refreshes and apparently nothing happens, the XML is the same as before. What did i do wrong? Also, i'd like to know if there's a better way of doing it.

Best Solution

is your code block copy and pasted from your existing files? if so i see two potential issues:

<form name='input' action'insert.php' method='post'> // should be:
<form name="input" action="insert.php" method="post">

note: you're missing action="insert.php", which would cause the form to just reload itself without submitting, which is the behaviour you describe.

secondly, make sure you have write permission to "sample.xml". you can confirm if you're actually writing anything:

print 'I wrote '.$xmldoc->save('sample.xml').' bytes of data';
Related Question