Php – Problems with deleting XML elements using PHP DOM


Here's the XML file i'm working on:


The index.php, page that shows the list of activities with checkboxes, a button to delete the checked activities, and a field to add new activities:

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

    $count = 0;

    $activities = $xmldoc->firstChild->firstChild;
    //prints the list of activities, with checkboxes on the left for each item
    //the $count variable is the id to each entry
        echo '<form name=\'erase\' action=\'delete.php\' method=\'post\'>' . "\n";
            echo "    <input type=\"checkbox\" name=\"activity[]\" value=\"$count\"/>";
            echo ' '.$activities->textContent.'<br/>'."\n";
            $activities = $activities->nextSibling;
        echo '    <input type=\'submit\' value=\'erase selected\'>';
        echo '</form>';
//section used for inserting new entries. this feature is working as expected.
<form name='input' action='insert.php' method='post'>
    insert activity:
    <input type='text name='activity'/>
    <input type='submit' value='send'/>

the delete.php, which is not working as expected:

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

    $atvID = $_POST['activity'];

    foreach($atvID as $id){
        $delnode = $xmldoc->getElementsByTagName('activity');


I've tested the deletion routine without the loop, using an hard-coded arbitrary id, and it worked. I also tested the $atvID array, and it printed the selected id numbers correctly. When it is inside the loop, here's the error it outputs:

Catchable fatal error: Argument 1
passed to DOMNode::removeChild() must
be an instance of DOMNode, null given
on line 9

What is wrong with my code?

Best Solution

the DOMNodeList items are indexed starting with 0; You need to move the $count++ to the end of the while loop in the output step.