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

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

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


    
    

        
17条回答
  •  猫巷女王i
    2020-11-22 03:01

    Contrary to popular belief in the existing answers, each Simplexml element node can be removed from the document just by itself and unset(). The point in case is just that you need to understand how SimpleXML actually works.

    First locate the element you want to remove:

    list($element) = $doc->xpath('/*/seg[@id="A12"]');
    

    Then remove the element represented in $element you unset its self-reference:

    unset($element[0]);
    

    This works because the first element of any element is the element itself in Simplexml (self-reference). This has to do with its magic nature, numeric indices are representing the elements in any list (e.g. parent->children), and even the single child is such a list.

    Non-numeric string indices represent attributes (in array-access) or child-element(s) (in property-access).

    Therefore numeric indecies in property-access like:

    unset($element->{0});
    

    work as well.

    Naturally with that xpath example, it is rather straight forward (in PHP 5.4):

    unset($doc->xpath('/*/seg[@id="A12"]')[0][0]);
    

    The full example code (Demo):

    
        
        
        
        
        
    
    DATA;
    
    
    $doc = new SimpleXMLElement($data);
    
    unset($doc->xpath('seg[@id="A12"]')[0]->{0});
    
    $doc->asXml('php://output');
    

    Output:

    
    
        
        
    
        
        
    
    

提交回复
热议问题