Umair Umair - 4 months ago 36
PHP Question

Use FILTER() inside Foreach loop - PHP Goutte

I have this code

require_once 'vendor/autoload.php';

use Symfony\Component\DomCrawler\Crawler;

$html = <<<'HTML'
<!DOCTYPE html>
<html>
<body>
<p class="message">Hello World!
<span>This is span</span>
</p>
<p>Hello Crawler!
<span>This is span</span>
</p>
</body>
</html>
HTML;

$crawler = new Crawler($html);

foreach ($crawler->filter('body') as $domElement) {
$domElement->filter('span');
}


I am getting this error .

Fatal error: Call to undefined method DOMElement::filter()


I need to know how do I select elements using
CSS Selectors
inside that Foreach loop?

I searched a lot but did not find anything.

Answer

You can just use this.

$crawler = new Crawler($html);

$crawler->filter('body')->each(function(Crawler $node, $i){
    return $node->filter('span');
});
Comments