我有这个代码
require_once 'vendor/autoload.php';
使用 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');
}
我遇到了这个错误。
Fatal error: Call to undefined method DOMElement::filter()
我需要知道如何在 Foreach 循环中使用 CSS 选择器
选择元素?
我搜索了很多,但没有找到任何东西。
最佳答案
只需使用您在 docs 中的示例即可
$crawler = new Crawler($html);
$crawler->filter('body')->each(function(Crawler $node, $i){
return $node->filter('span');
});
或者执行 ->each(\Closure $closure)
函数在后台执行的工作:在循环内实例化爬虫节点
foreach ($crawler->filter('body') as $domElement) {
$domElement = new Crawler($domElement);
$domElement->filter('span');
}
关于php - 在 Foreach 循环中使用 FILTER() - PHP Goutte,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38466668/