屏幕抓取带有 PHP 的两列表


Screen scraping a two-column table with PHP

听起来很简单,但我对整个屏幕抓取的事情很陌生。我有一个远程站点 http://www.remotesite.com(例如目的),它有一个结构如下的时间表:

<table>
  <tr>
    <td class="team">
      Team 1
    </td>
    <td class="team">
      Team 2
    </td>
  </tr>
</table>

该表填充了一个动态条目范围,具体取决于当天球队 1 对球队 2 等的游戏数量。

我已经构建了我的刮板来获取表中列出的所有团队的列表,并且它工作成功。代码如下:

<?php
// Load Simple DOM
    include_once("simple_html_dom.php");
    
// Scrape the Schedule
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $html = file_get_html("http://www.remotesite.com/schedule.htm");
    
    // Load HTML
        $dom->loadHTML($html);
        $xpath = new DOMXPath($dom);
    // Get all the Teams
        $my_xpath_query = "//table//td[contains(@class, 'team')]";
        $result_rows = $xpath->query($my_xpath_query);

?>

为了回应刮擦,我有以下代码:

<?php
    // Display the schedule
        foreach ($result_rows as $result_object){
            echo $result_object->nodeValue;
        }
?>

但是,这样做的作用是像这样呼应团队:

Team1Team2Team3Team4Team5Team6 etc, etc.

它以正确的顺序让对阵的球队对阵,但我需要做的基本上是以与获取表格相同的方式回显表格。

提前感谢您给我的任何帮助!

根据你对我问题的回答,我建议做这样的事情:

$rows = '';
$teams = array();
// Pull team names into array
foreach ($result_rows as $result_object){
   $teams[] = $result_object->nodeValue;
}
// Extract two teams per table row
while(count($teams)){
   $matchup = array_splice($teams, 0, 2);
   $rows .= '<tr><td>'.implode('</td><td>', $matchup).'</td></tr>';
}
// Write out the table
echo "<table>$rows</table>';