php - 在 Foreach 循环中使用 FILTER() - PHP Goutte

标签 php symfony goutte

我有这个代码

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/

相关文章:

php - 如何在blueimp文件 uploader 中传递值?

php - 无法使用 PHP 从 MySQL 获取数据

php - MYSQLI_TYPE_INTERVAL 有什么用?

symfony - 使用 FosUserBundle 创建管理员用户

php - Goutte-dom爬虫-移除节点

javascript - 如何在一个固定根上设置 Service Worker

php - 用户测试中多个客户端的 Symfony 4.4 弃用警告已弃用,仍存在于文档中

symfony - 使用 Silex 自定义路由配置

php - 如何在Goutte中下载图像

php - Behat:Goutte/Guzzle 通过 cURL "Warning: curl_setopt_array(): 3607 is not a valid File-Handle resource"下载文件