gpt4 book ai didi

php - Symfony2 DomCrawler 从 DOMElement 移除节点

转载 作者:行者123 更新时间:2023-12-04 20:35:44 24 4
gpt4 key购买 nike

我有这个 HTML:

<div class="body">
<p>Some text 1</p>
<h2>Header 2</h2>
<p>Actual content</p>
</div>

我想从中得到除<h2>以外的一切所以它看起来像这样:

<p>Some text 1</p>
<p>Actual content</p>

试图实现这一目标:

$crawler = new Crawler( $html );

$body = $crawler->filter( 'div.body' );
$body->rewind();
$body = $body->current();

$h2 = $crawler->filter('h2');
$h2->rewind();
$h2 = $h2->current();

$body->removeChild($h2);

但是我得到:

[DOMException] Not Found Error

我错过了什么?

最佳答案

作为explained in the docs :

The DomCrawler component eases DOM navigation for HTML and XML documents.

还有:

While possible, the DomCrawler component is not designed for manipulation of the DOM or re-dumping HTML/XML.

DomCrawler 旨在从 DOM 文档中提取详细信息,而不是修改它们。

但是……

由于 PHP 通过引用传递对象,Crawler 基本上是 DOMNode 的包装器s,在技术上可以修改底层 DOM 文档:

// will remove all h2 nodes inside .body nodes
$crawler->filter('.body h2')->each(function ($crawler) {
foreach ($crawler as $node) {
$node->parentNode->removeChild($node);
}
});

这是一个工作示例:https://gist.github.com/jakzal/8dd52d3df9a49c1e5922

关于php - Symfony2 DomCrawler 从 DOMElement 移除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19177578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com