How to edit html of elements? I tried this, but i get this error.
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());
});
Use this:
$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
DOMDocumentobject for creating new tag that used inCrawlerobject.
As explained in The DomCrawler Component docs:
An instance of the Crawler represents a set of DOMElement objects, which are nodes that can be traversed...
So, you need to traverse Crawler object before manipulate DOMElements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With