Search code examples
phpsimplexmlxmldocumentxmldom

How to delete a SimpleXMLElement?


I posted a question regarding this about how to figure attribute values before. Even though I figured that I cannot delete the element which has this attribute. I try searching but still I can't find a proper working answer. I really hope you can help me. This is my code. I go though xml document looking for the attribute value and then try to delete the parent node of the node that has this attribute value.

        $xml = new SimpleXMLElement($xmlfile,0,true);

        $results = $xml->xpath("/presets/preset");

        foreach ($results as $result) {
        foreach ($result->children() as $second_gen) {
            if($second_gen->getName()=='name'){
                foreach($second_gen->attributes() as $a => $b) {
                    if($b==$preset_name){
                        echo($b);
                            echo($preset_name);
                            unset($result);
                        }

                }
            }

        }
        }
        $xml->asXML();

As a result of executing this code I get no errors and I have correct $b and $preset_name echoed. But node is not getting deleted. It's still there in the document.

My xml file looks like:

 <presets>
 <preset>
 <name code="default">Default</name>
  <createdBy>p</createdBy>
   <icons>q</icons>
 </preset>
 <preset>
   <name code="new_preset">New Preset</name>
    <createdBy>x</createdBy>
   <icons>y</icons>
 </preset>
 ...
 </presets>

Solution

  • I found a simple answer without using SimpleXMLElement class. Check this out for my complete answer. How can i get the value of attribute in of a xml node in php?