Remove a child with a specific attribute, in SimpleXML for PHP

后端 未结 17 2383
星月不相逢
星月不相逢 2020-11-22 02:50

I have several identical elements with different attributes that I\'m accessing with SimpleXML:


    
    

        
17条回答
  •  不知归路
    2020-11-22 02:51

    For future reference, deleting nodes with SimpleXML can be a pain sometimes, especially if you don't know the exact structure of the document. That's why I have written SimpleDOM, a class that extends SimpleXMLElement to add a few convenience methods.

    For instance, deleteNodes() will delete all nodes matching a XPath expression. And if you want to delete all nodes with the attribute "id" equal to "A5", all you have to do is:

    // don't forget to include SimpleDOM.php
    include 'SimpleDOM.php';
    
    // use simpledom_load_string() instead of simplexml_load_string()
    $data = simpledom_load_string(
        '
            
            
            
            
            
        '
    );
    
    // and there the magic happens
    $data->deleteNodes('//seg[@id="A5"]');
    

提交回复
热议问题