2013-11-15 87 views
0

我有一個看似獨特的情況,我想使用DOMDocument查找頁面上的節點,將其存儲到變量(工作),然後將其從輸出中刪除它。我無法弄清楚如何從DOMDocument輸出中刪除節點,並仍然先保存它的值。複製和刪除節點與PHP DOMDocument

我能夠首先完全刪除節點,這意味着沒有任何內容存儲在變量中,或者在嘗試刪除節點時收到「未找到錯誤」。

頁面上只有一個節點(<h6>)需要刪除。我到目前爲止的代碼(未找到錯誤)在下面。

// Strip Everything Before and After Header Tags 
$domdoc = new DOMDocument; 
$docnew = new DOMDocument; 

// Disable errors for <article> tag 
libxml_use_internal_errors(true); 
$domdoc->loadHTML(file_get_contents($file)); 
libxml_clear_errors(); 

$body = $domdoc->getElementsByTagName('body')->item(0); 

foreach ($body->childNodes as $child){ 
    $docnew->appendChild($docnew->importNode($child, true)); 
} 

// Get the Page Title 
$ppretitle = $docnew->getElementsByTagName('h6')->item(0); 
$pagetitle = $ppretitle->nodeValue; 

// Remove Same Element From Output 
$trunctitl = $docnew->removeChild($ppretitle); 

// Save Cleaned Output In Var 
$pagecontent = $docnew->saveHTML(); 
+1

我們可以看到一個示例HTML能夠重現問題? – Passerby

回答

0

h6元素可能不是body元素的直接子節點:儘量$ppretitle->parentNode->removeChild($ppretitle)代替$trunctitl = $docnew->removeChild($ppretitle);

+0

工作!謝謝 – user1766072