使用DOMDocument删除php中的XML元素

时间:2013-12-31 17:44:00

标签: php xml domdocument

大家好我有一个简单的XML文档:

<iPhone>
 <enAttente>
  <UDID>value</UDID>
  <adresse>value</adresse>
 </enAttente>
 <enAttente>
  <UDID>value</UDID>
  <adresse>value</adresse>
 </enAttente>
</iPhone>

我想删除&lt; enAttente&gt; ,其中&lt; adresse&gt; = myValue 这就是我所做的:

$doc = new DOMDocument;   
$doc->load('./folder/myFile.xml');  
if ($doc)
{
    $domNodeList = $doc->getElementsByTagname('enAttente');

    for ($i = 0; $i < count($array); $i++)
    {
        foreach ($domNodeList as $domElement ) {
         $authors = $domElement->getElementsByTagName( "adresse" );
         $author = $authors->item(0)->nodeValue;

         if ($author == "myValue")
         {
             echo"Founded ! Delete this node ! -- ";
             // HOW CAN I DELETE this <enAttente> !!
         }
        }
    }

    $doc->saveXML();      
}

当我找到要删除的元素时,有人可以删除元素吗? 非常感谢你 !

2 个答案:

答案 0 :(得分:1)

在我看来,你需要

$domElement->parentNode->removeChild($domElement);

答案 1 :(得分:0)

好的,这里有一些工作代码:

<?php
$file = './folder/myFile.xml';
$doc = new DOMDocument;   
$doc->load($file);  
if ($doc)
{
    $domNodeList = $doc->getElementsByTagname('enAttente');

    foreach ($domNodeList as $domElement ) {
        $authors = $domElement->getElementsByTagName('adresse');
        $firstNode = $authors->item(0);

        $author = $firstNode->nodeValue;
        if ($author == "myValue")
        {
            echo "Founded ! Delete this node ! -- ";
            $doc->documentElement->removeChild($domElement);
        }
    }

    $doc->save($file);      
}