如何使用Goutte/Domcrawler组合2条提取数据的文本节点


How to combine the text node of 2 pieces of extracted data using Goutte/Domcrawler

我一直在试图弄清楚如何将两段提取的文本组合成一个结果(数组)。在这种情况下,各种书籍的标题和副标题。

<td class="item_info">
  <span class="item_title">Carrots Like Peas</span>
  <em class="item_subtitle">- And Other Fun Facts</em>
</td>

我能得到的最接近的是:

$holds = $crawler->filter('span.item_title,em.item_subtitle');

我设法通过以下方式输出:

$holds->each(function ($node) {
    echo '<pre>';
    print $node->text();
    echo '</pre>';
});

并导致

<pre>Carrots Like Peas</pre>
<pre>- And Other Fun Facts</pre>

另一个问题是并非所有的书都有字幕,所以我需要避免将两个标题组合在一起。我将如何将这两者合并为一个结果(或数组)?

就我而言,我采取了一种迂回的方式到达我想去的地方。我在 DOM 中退后一级到 td 标签,然后抓取所有内容并将其转储到数组中。

我意识到 DomCrawler 的文档包含将文本节点放入数组的示例代码。

$items_out = $crawler->filter('td.item_info')->each(function (Crawler $node, $i) {
    return $node->text();   
});

我试图避免捕获td,因为作者也包含在这些单元格中。经过更多的挖掘,我能够使用以下方法从数组中剥离作者:

foreach ($items_out as &$items) {
    $items = substr($items,0, strpos($items,' - by'));
}

我花了五天时间就把它整理好了。现在进入下一个问题!

根据Goutte文档,Goutte使用Symfony DomCrawler组件。 有关向DomCrawler对象添加内容的信息可以在Symfony DomCrawler - 添加内容中找到