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

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

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


    
    

        
17条回答
  •  轮回少年
    2020-11-22 03:16

    Idea about helper functions is from one of the comments for DOM on php.net and idea about using unset is from kavoir.com. For me this solution finally worked:

    function Myunset($node)
    {
     unsetChildren($node);
     $parent = $node->parentNode;
     unset($node);
    }
    
    function unsetChildren($node)
    {
     while (isset($node->firstChild))
     {
     unsetChildren($node->firstChild);
     unset($node->firstChild);
     }
    }
    

    using it: $xml is SimpleXmlElement

    Myunset($xml->channel->item[$i]);
    

    The result is stored in $xml, so don’t worry about assigning it to any variable.

提交回复
热议问题