Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting simplexmlelement node [duplicate]

Tags:

php

xml

simplexml

I have an xml file of this structure

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

To delete an event, I have this php function.

<?php

include_once("phpshared.php");

function delete_event( $nodeid ) {

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

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

    $node->parentNode->removeChild($node);

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

}

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

?>

That doesn't delete the node. Is there a different way to do this?

like image 492
user823527 Avatar asked Mar 10 '12 01:03

user823527


2 Answers

SimpleXML allows removal of elements via PHP's unset() keyword.

For your code snippet, simply replace

$node->parentNode->removeChild($node);

with

if ( ! empty($node)) {
    unset($node[0][0]);
}

If the XPath query returned a matching <event> element, we instruct SimpleXML to unset() it.


Aside: here are two occurrences of [0] because:

  • xpath() returns an array, even if only one element matches. So [0] is used to get the first item in that array, which is the element we want to delete.
  • The SimpleXMLElement returned from $node[0] represents a collection of <event> elements (but if you access elements/attributes on it then the values from the first in the collection is used). So, we use [0] to get at the actual SimpleXMLElement that we want to delete, which is the first in this magical collection.
like image 59
salathe Avatar answered Oct 21 '22 14:10

salathe


Use unset(): Remove a child with a specific attribute, in SimpleXML for PHP

like image 26
Radek Avatar answered Oct 21 '22 15:10

Radek