gpt4 book ai didi

php - Symfony DOMCrawler : How to change html?

转载 作者:行者123 更新时间:2023-12-04 02:42:18 24 4
gpt4 key购买 nike

如何编辑元素的html?我试过这个,但我收到这个错误。

Fatal error: Uncaught InvalidArgumentException: Attaching DOM nodes from multiple documents in the same crawler is forbidden.


$crawler = new Crawler('<h1>The title</h1>');
$crawler
->filter('h1,h2,h3,h4,h5,h6')
->each(function (Crawler $crawler, $i) use (&$replace) {
$crawler->html('<span>test</span>' . $crawler->html());
});

最佳答案

用这个:

$doc = new DOMDocument;
$doc->loadHTML($html);
$crawler = new Crawler($doc);

$crawler
->filter('h1,h2,h3,h4,h5,h6')
->each(function (Crawler $crawler) use ($doc) {
foreach ($crawler as $node) {
$span = $doc->createElement('span', 'test');
$node->parentNode->insertBefore($span, $node);
}
});

Important: Use same DOMDocument object for creating new tag that used in Crawler object.



The DomCrawler Component 中所述文档:

An instance of the Crawler represents a set of DOMElement objects, which are nodes that can be traversed...



所以,你需要遍历 Crawler操作前的对象 DOMElements .

关于php - Symfony DOMCrawler : How to change html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58806401/

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