使用DOM和PHP删除XML文件的子节点

时间:2014-05-14 06:18:27

标签: php dom

我正在尝试使用DOM和PHP删除XML文档中的子节点,但我无法弄清楚如何执行此操作。我无法访问simpleXML。

XML布局:

<list>
  <as>
     <a>
       <a1>delete</a1>
     </a>
     <a>
       <a1>keep</a1>
     </a>
  </as>
<list>

PHP代码:

$xml = "file.xml";
$dom = DOMDocument::load($xml);
$list = $dom->getElementsByTagName('as')->item(0);

//Cycle through <as> elements (there are multiple in the full file)
foreach($list->childNodes as $child) {
    $subChild = substr($child->tagName, 0, -1);
    $a = $dom->getElementsByTagName($subChild);
            //Cycle through <a> elements
    foreach($a as $node)
    {
        //Get status for status check
        $check= $node->getElementsByTagName("a1")->item(0)->nodeValue;
        if(strcmp($check,'delete')==0)
        {
                         //code to delete here (I wish to delete the <a> that this triggers
        }
    }
}

1 个答案:

答案 0 :(得分:1)

http://www.php.net/manual/en/class.domnode.php

http://www.php.net/manual/en/domnode.removechild.php

您需要节点的父节点将其删除,并且您已将其作为要删除的节点的属性,因此没有大问题。结果将是:

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