Question

I'm trying to delete a child node within a XML document using DOM and PHP but I can't quite figure out how to do it. I do not have access to simpleXML.

XML Layout:

<list>
  <as>
     <a>
       <a1>delete</a1>
     </a>
     <a>
       <a1>keep</a1>
     </a>
  </as>
<list>

PHP Code:

$xml = "file.xml";
$dom = DOMDocument::load($xml);
$list = $dom->getElementsByTagName('as')->item(0);

//Cycle through <as> elements (there are multiple in the full file)
foreach($list->childNodes as $child) {
    $subChild = substr($child->tagName, 0, -1);
    $a = $dom->getElementsByTagName($subChild);
            //Cycle through <a> elements
    foreach($a as $node)
    {
        //Get status for status check
        $check= $node->getElementsByTagName("a1")->item(0)->nodeValue;
        if(strcmp($check,'delete')==0)
        {
                         //code to delete here (I wish to delete the <a> that this triggers
        }
    }
}
Was it helpful?

Solution

http://www.php.net/manual/en/class.domnode.php

http://www.php.net/manual/en/domnode.removechild.php

You need the parent of a node to remove it, and you've got it as a property of the node that you want to remove, so no biggie. The result would be:

$node->parentNode->removeChild($node);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top