Eliminando el nodo simplexmlelement [duplicado]

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 delete 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']));


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

preguntado el 10 de marzo de 12 a las 01:03

2 Respuestas

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

For your code snippet, simply replace



if ( ! empty($node)) {

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

Aparte: here are two occurrences of [0] porque:

  • 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] representa una colección de <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.

respondido 10 mar '12, 14:03

Thanks for the answer. I went with the other option because I want to be able to access the node as a DOM. - user823527

That's not what your question asked. - Salathe

@salathe point about the second [0] index was particularly helpful and is a big gotcha. - Dom

contestado el 23 de mayo de 17 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.