簡體   English   中英

使用DOM和PHP刪除XML文件的子節點

[英]Removing the child node of an XML file using DOM and PHP

我正在嘗試使用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
        }
    }
}

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

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

您需要一個節點的父節點來刪除它,並且已經將它作為要刪除的節點的屬性,所以這沒什么大不了的。 結果將是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM