5

我的网站上有 html(http://testsite.com/test.php):

<div class="first">
  <div class="second">
     <a href="/test.php">click</a>
     <span>back</span>
  </div>
</div>
<div class="first">
  <div class="second">
     <a href="/test.php">click</a>
     <span>back</span>
  </div>
</div>

我想收到:

<div class="first">
  <div class="second">
     <a href="/test.php">click</a>
  </div>
</div>
<div class="first">
  <div class="second">
     <a href="/test.php">click</a>
  </div>
</div>

所以我想删除跨度。我基于http://symfony.com/doc/current/components/dom_crawler.html在 Symfony2 中使用 Goutte :

    $client = new Client();
    $crawler = $client->request('GET', 'http://testsite.com/test.php');

    $crawler->filter('.first .second')->each(function ($node) {
        //??????
    });
4

2 回答 2

5

文档中所述

DomCrawler 组件简化了 HTML 和 XML 文档的 DOM 导航。

并且:

尽管可能,DomCrawler 组件并不是为操作 DOM 或重新转储 HTML/XML 而设计的。

DomCrawler 旨在从 DOM 文档中提取细节而不是修改它们。

然而...

由于 PHP 通过引用传递对象,而Crawler基本上是DOMNode的包装器,因此在技术上可以修改底层 DOM 文档:

// will remove all span nodes inside .second nodes
$crawler->filter('html .content h2')->each(function (Crawler $crawler) {
    foreach ($crawler as $node) {
        $node->parentNode->removeChild($node);
    }
});

这是一个工作示例:https ://gist.github.com/jakzal/8dd52d3df9a49c1e5922

于 2015-04-01T21:15:18.793 回答
-1

To remove a node the anonymous function must return false.

只需在 reducer 内返回 false,$node 就会被删除。

于 2014-10-21T19:46:38.227 回答