首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用PHP DOMDocument复制和删除节点

用PHP DOMDocument复制和删除节点
EN

Stack Overflow用户
提问于 2013-11-15 08:38:01
回答 1查看 72关注 0票数 0

我有一个看似独特的情况,我想使用DOMDocument在页面上找到一个节点,将它的值存储到变量中(工作中),然后从输出中删除它。我不知道如何从DOMDocument输出中删除该节点,同时仍然首先保存它的值。

我可以先完全删除节点,这意味着变量中没有存储任何内容,或者在尝试删除节点时收到“Not Found Error”。

页面上只有一个节点(<h6>)需要删除。我到目前为止的代码(没有发现错误)如下所示。

代码语言:javascript
运行
复制
// 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();
EN

回答 1

Stack Overflow用户

发布于 2013-11-15 16:48:53

h6元素可能不是body元素的直接子节点:请尝试使用$ppretitle->parentNode->removeChild($ppretitle)而不是$trunctitl = $docnew->removeChild($ppretitle);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19991347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档