格式化刮擦数据 - 并限制foreach循环

问题描述 投票:1回答:1

我用下面的代码解决了我的初始问题。我现在需要学习如何将返回的数据限制为前5行。如何限制foreach循环?

我正在从site抓取数据 - 我能够遍历DOM以获得我想要的表“最后1个月(11/20 / 2017-12 / 19/2017)”,这是第3个或“2”。但是,我无法确保输出正确。我需要将它包装在一个表中,每行包含代码中指定的td。以下是我使用的代码,但成功有限:

<?php
    $html = file_get_contents('https://ninjatrader.isystems.com/Systems/TopStrategies'); 
    $doc = new DOMDocument();
    @$doc->loadhtml($html);
    $xpath = new DOMXPath($doc);

    echo "<table>";
    foreach($xpath->query('//table')->item(2)->getElementsByTagName('tr') as $rows) {
    $cells = $rows->getElementsByTagName('td');

    echo "<tr>
            <td>" . $cells->item(1)->textContent . "</td>
                <td>" . $cells->item(2)->textContent . "</td>
                <td>" . $cells->item(3)->textContent . "</td>
                <td>" . $cells->item(5)->textContent . "</td>
            </tr>";
    }
    echo "</table>";
?>

好的,我已经解决了上述问题。有一个更好的方法吗?

php web-scraping
1个回答
1
投票

您可以通过nodeName属性访问标记名称,然后将标记的其他部分作为字符串添加到输出中。

echo "<" . $cells->item(1)->nodeName . ">";
echo $cells->item(1)->textContent;
echo "</" .  $cells->item(1)->nodeName . ">";

对“td”元素更有说服力的方法:

for($i = 1; $i < 6; $i++)
{        
    if ($i != 4 && $cells->length > 4) {
         echo "<td>" . $cells->item($i)->textContent . "</td>";
    }
}

对于主循环,我会像这样写,并将每个元素输出到一个新行。如果不需要新行,请删除“\ n”。您可以使用数组键将foreach循环限制为$ index。由于在这种情况下第0行为空,因此获取前5行是$index < 6。如果第0行有数据,则可以使用$index < 5

$rows = $xpath->query('//table')->item(2)->getElementsByTagName('tr');
echo "<table>\n";
foreach($rows as $index => $row) {
  $cells = $row->getElementsByTagName('td');
  if ($cells->length > 4 && $index < 6) {
    echo "<tr>\n";
    for($i = 1; $i < 6; $i++)
    {        
      if ($i != 4) {
        echo "<td>" . $cells->item($i)->textContent . "</td>\n";
      }
    }
    echo "</tr>\n";
  }
}
echo "</table>\n";

参考文献:

http://php.net/manual/en/class.domxpath.php

http://php.net/manual/en/control-structures.for.php

http://php.net/manual/en/control-structures.foreach.php

© www.soinside.com 2019 - 2024. All rights reserved.