我有一个看似独特的情况,我希望使用DOMDocument在页面上查找节点,将其值存储到变量(工作)中,然后将其从输出中删除。我无法弄清楚如何从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();
答案 0 :(得分:0)
h6
元素可能不是body
元素的直接子节点:尝试$ppretitle->parentNode->removeChild($ppretitle)
而不是$trunctitl = $docnew->removeChild($ppretitle);