Removing a simplex node

I have an xml file of this structure

<?xml version="1.0" encoding="iso-8859-1"?>
                        <event id="e20111129215359">
                            <title>the title</title>
                            <channel id="1">
                                <name>A name</name>
                            <start_date>Thu Mar 08 2012</start_date>
                            <start_time>11:00 AM</start_time>
                            <notes>Notes for the event</notes>


To remove an event, I have this php function.



function delete_event( $nodeid ) {

    $nodes = new SimpleXMLElement('my_events.xml', LIBXML_NOCDATA, true);

    $node = $nodes->xpath("/my_events/event[@id='$nodeid']");


    $formatted = formatXmlString($nodes->asXML());
    $file = fopen ('my_events.xml', "w"); 
    fwrite($file, $formatted); 
    fclose ($file);  


echo delete_event(trim($_REQUEST['nodeid']));



This does not remove node. Is there any other way to do this?


source to share

2 answers

Use unset()

: Remove child with specific attribute in SimpleXML for PHP



SimpleXML allows you to remove elements using the PHP keyword unset()


For your code snippet, just replace




if ( ! empty($node)) {


If the XPath query returned a matching element <event>

, we will instruct SimpleXML on unset()


Also: here are two occurrences [0]


  • xpath()

    returns an array even if only one element matches. So it is [0]

    used to get the first element in this array, which is the element we want to remove.
  • The SimpleXMLElement returned from $node[0]

    is a collection of elements <event>

    (but if you access elements / attributes on it, then the values ​​from the first in the collection are used). So, we use [0]

    to get the actual SimpleXMLElement

    one we want to delete, which is the first in this magic collection.


All Articles