在PHP中从XML文件中删除元素

时间:2012-03-22 22:12:51

标签: php xml removechild

我试图用以前的答案找出来,但我不能正确地做到这一点,我跟着斯特凡的回答Remove a child with a specific attribute, in SimpleXML for PHP

我的代码是

的xml:

    <?xml version="1.0" encoding="utf-8"?>
    <res>
    <items>
    <item>
    <id>1</id>
    <a>asdasda</a>
    </item>
    <item>
    <id>1</id>
    <a>bababba</a>
    </item>
    <id>2</id>
    <a>sasdasda</a>
    </item>
    <item>       
    <id>3</id>
    <a>sasdasda</a>
    </item>
    <item>
    <id>4</id>
    <a>sasdasda</a>
    </item>
    <item>
    <id>5</id>
    <a>sasdasda</a>
    </item>
    <item>
    <id>6</id>
    <a>sasdasda</a>
    </item>
    </items>
    </res>

和php是

   <?php
   $id="1";
   $xml = simplexml_load_file("filtracjaxml.xml") ;

   foreach($xml->items->item->id as $id)
   {
       if($id == '1') {
           $xml=dom_import_simplexml($id);
           $xml->parentNode->removeChild($xml);
       }
   }
   echo $xml->asXml();
   ?>

当我尝试运行它时,我有

    Fatal error: Call to undefined method DOMElement::asXml() in filtruj.php on line 14

编辑:

我想要的是删除整个'item'而不仅仅是'id' - 所有id = 1的项目

所以我改变了代码:

    foreach ( $xml->items->item as $id )
    {
        if ( $id->id == '1' ) {
            $tmp = dom_import_simplexml($id);
            $tmp->parentNode->removeChild($tmp);
        }
    }
    echo $xml->asXml();

并且它只删除第一个项目。你能告诉我为什么吗?上面写的代码有什么问题?

1 个答案:

答案 0 :(得分:1)

<?php
$id="1";
$xml = simplexml_load_file("filtracjaxml.xml") ;

foreach ( $xml->items->item->id as $id )
{
    if ( $id == '1' ) {
        $tmp = dom_import_simplexml($id);
        $tmp->parentNode->removeChild($tmp);
    }
}
echo $xml->asXml();
?>