2013-02-18 63 views
1

我尋找這個問題並找到了一些問題,但他們沒有提到我的錯誤...如何刪除XML DOM文檔中的PHP

我想刪除我的DOM文檔的子當我鍵入$x->removeChild($key);功能,沒有什麼happend ...

$xmlreq = new DOMDocument; 
$xmlreq->loadXML($xmlStr); 
$x = $xmlreq->getElementsByTagName('*'); 
foreach($x as $key) 
{ 
    if (substr($key->nodeValue,0,3)=="{{{" and substr($key->nodeValue,-3)=="}}}") 
    { 
     $field = explode("|",substr($key->nodeValue,3,strlen($key->nodeValue)-6)); 

     if((int)$field[3]==0) 
     { 
      if(trim($_POST[$field[2]])=="") 
      { 
       $x->removeChild($key); 
      }else{ 
       $key->nodeValue = trim($_POST[$field[2]]); 
      } 
     }elseif((int)$field[3]==1) 
     { 
      if(trim($_POST[$field[2]])=="") 
      { 
       $errors.=""; 
      }else{ 
       $key->nodeValue = trim($_POST[$field[2]]); 
      } 
     }else{ 

     } 



    } 
} 

header("content-type: application/xml"); 
print $xmlreq->saveXml(); 

,這是我的xml:

<epp xmlns="urn:ietf:params:xml:ns:epp-1.0"> 
<command> 
<check> 
<contact:check xmlns:contact="http://epp.nic.ir/ns/contact-1.0"> 
<contact:id>ghhg-ghgh</contact:id> 
<contact:id>45</contact:id> 
<contact:id>45</contact:id> 
<contact:id>45</contact:id> 
<contact:authInfo> 
<contact:pw>1561651321321</contact:pw> 
</contact:authInfo> 
</contact:check> 
</check> 
<clTRID>TEST-12345</clTRID> 
</command> 
</epp> 

,我想刪除的<contact:id>45</contact:id>

一個
+1

'的getElementsByTagName():該函數返回的elements.' – SparKot 2013-02-18 12:46:50

+0

所有匹配類的DOMNodeList的新實例,我用的foreach讓每一個元素 – Pooya 2013-02-18 12:49:35

+0

@DoSparKot是正確的 - 你已經在'$ x'中創建了'$ xmlreq'的副本,但是你不保存'$ x',或者可能稍後使用它。 – Raad 2013-02-18 13:01:42

回答

0

你的循環什麼也不做,因爲外部條件正在尋找一個節點,在nodeValue開始與{{{}}}結束:

foreach($x as $key) 
{ 
    if (substr($key->nodeValue,0,3)=="{{{" and substr($key->nodeValue,-3)=="}}}") 

此外,還有在DOMNodeList沒有removeChild()方法。您可能想首先獲取節點的父節點,然後調用removeChild()方法。

另一種可能:

$x = $xmlreq->getElementsByTagName('*'); 
$remove = TRUE; 
foreach($x as $key) 
{ 
    if($key->nodeName=='contact:id' && $key->nodeValue=='45'){ 
     if($remove){ 
      $key->parentNode->removeChild($key); 
      $remove = FALSE; 
     } 
    } 
}