wasinger / htmlpagedom

jQuery-inspired DOM manipulation extension for Symfony's Crawler
MIT License
346 stars 50 forks source link

Cannot replace root element when multiple root node #21

Open shtse8 opened 7 years ago

shtse8 commented 7 years ago

Code:

$c = new HtmlPageCrawler('<p>Paragraph 1</p> <p>Paragraph 2</p><p>Paragraph 3</p>');
$c->filter('p')->first()->each(function($element) {
    $element->replaceWith('ff');
});
echo $c->saveHTML();

Expected:

ff <p>Paragraph 2</p><p>Paragraph 3</p>

Actual:

<p>Paragraph 1</p> <p>Paragraph 2</p><p>Paragraph 3</p>
shtse8 commented 7 years ago

But it works with:

$c = new HtmlPageCrawler('<div><p>Paragraph 1</p> <p>Paragraph 2</p><p>Paragraph 3</p></div>');
$c->filter('p')->first()->each(function($element) {
    $element->replaceWith('ff');
});
echo $c->saveHTML();

Result:

<div>ff <p>Paragraph 2</p> <p>Paragraph 3</p></div>
shtse8 commented 7 years ago

Error occurs in the following code:

$c = new HtmlPageCrawler('<p>Paragraph 1</p> <p>Paragraph 2</p><p>Paragraph 3</p>');
$c->filter('p')->first()->each(function($element) {
    $element->replaceWith('ff');
});
$c->filter('p')->first()->each(function($element) {
    $element->replaceWith('dd');
});
echo $c->saveHTML();

Result:

PHP Fatal error:  Uncaught Error: Call to a member function replaceChild() on null in /var/www/site/www/core/vendor/wa72/htmlpagedom/src/HtmlPageCrawler.php:652
Stack trace:
#0 /var/workspace/test10.php(13): Wa72\HtmlPageDom\HtmlPageCrawler->replaceWith(Object(Wa72\HtmlPageDom\HtmlPageCrawler))
#1 /var/www/site/www/core/vendor/symfony/dom-crawler/Crawler.php(371): {closure}(Object(Wa72\HtmlPageDom\HtmlPageCrawler), 0)
#2 /var/workspace/test10.php(14): Symfony\Component\DomCrawler\Crawler->each(Object(Closure))
#3 {main}
  thrown in /var/www/site/www/core/vendor/wa72/htmlpagedom/src/HtmlPageCrawler.php on line 652
helariL commented 6 years ago

Any feedback for this? This is quite annoying....