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

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

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


    
    

        
17条回答
  •  迷失自我
    2020-11-22 03:13

    If you extend the base SimpleXMLElement class, you can use this method:

    class MyXML extends SimpleXMLElement {
    
        public function find($xpath) {
            $tmp = $this->xpath($xpath);
            return isset($tmp[0])? $tmp[0]: null;
        }
    
        public function remove() {
            $dom = dom_import_simplexml($this);
            return $dom->parentNode->removeChild($dom);
        }
    
    }
    
    // Example: removing the  element with id = 1
    $foo = new MyXML('');
    $foo->find('//bar[@id="1"]')->remove();
    print $foo->asXML(); // 
    

提交回复
热议问题