Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony DOMCrawler: How to change html?

Tags:

php

symfony

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());
    });
like image 654
Alexander Myravjev Avatar asked Oct 19 '25 04:10

Alexander Myravjev


1 Answers

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 DOMDocument object for creating new tag that used in Crawler object.

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.

like image 61
Alexander Yancharuk Avatar answered Oct 21 '25 20:10

Alexander Yancharuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!