Latest: Genstatic, my first sip of coffee

Content with Style

Web Technique

Remove nodes in SimpleXMLElement

by Matthias Willerich on July 15 2009, 18:56

SimpleXML provides no way to remove [...] XML nodes.

You might think otherwise and hack it with unset(), as it was done in one of the web applications I inherited at work, but today I found out that this works under some conditions, but not with every setup. I'd love to tell you what exactly the differences are that make it break, but I didn't spend the time tracking it down.

I can tell you what unset() did the the specific setup (PHP 5.1.2 on Windows Vista): Nothing. It happily executed it without error or warning, but also without changing anything.

Luckily S. Gehrig had a good and in my eyes not-hacky idea in a thread on stackoverflow.com: He suggests to use the DOM, specifically dom_import_simplexml(), to then simply use removeChild().

In my case I had a predictable XML structure to parse, and only needed to kick out the first of a set of nodes, so my solution (using the same xml setup as example) is as follows:


$data='<data>
    <seg id="A1"/>
    <seg id="A5"/>
    <seg id="A12"/>
    <seg id="A29"/>
    <seg id="A30"/>
</data>';
$doc=new SimpleXMLElement($data);
$dom=dom_import_simplexml($doc->seg[0]);
$dom->parentNode->removeChild($dom);
echo $doc->asXml();
/*outputs: 
 * <?xml version="1.0"?>
 * <data><seg id="A5"/><seg id="A12"/><seg id="A29"/><seg id="A30"/></data>
 */

For more complex XML structures (and probably closer to most real-life scenarios), I agree with S. in suggesting xpath as a way to detect your unwanted node.

Comments

  • Excelent article! Every other solution involves iterating through the $dom object!

    Thanks!

    Might I add, I used your example in an XML loaded from a file and with a node which I found using XPATH

    
    $file = 'test.xml';
    $xml=simplexml_load_file($file);
    $nodes = $xml->xpath("node()[@id=\"{$_GET['id']}\"]");
    $dom=dom_import_simplexml($nodes[0]);
    $dom->parentNode->removeChild($dom);
    

    Thanks again!

    by Fabricio on August 3 2010, 14:33 - #


Comments for this article are closed.