如何使用 simple_html_dom 或 Dom 文档跳过最后 n 行?

How to skip last n rows with simple_html_dom or Dom Document?

提问人:Chris 提问时间:4/10/2018 最后编辑:Brian Tompsett - 汤莱恩Chris 更新时间:4/10/2018 访问量:147

问:

有没有办法通过 simple_html_dom 或 dom 文档始终跳过解析表的最后 n 行?

我尝试使用固定的行号,但由于源文件可以更改其行数,因此没有成功。

这是我解析表的标准代码。你对我有想法或提示吗,如何跳过总是最后两行?

$table = $html->find('table', 1);
$rowData = array();

    foreach($table->find('tr') as $row) {
        // initialize array to store the cell data from each row

    $roster = array();
        foreach($row->find('td') as $cell) {
        $roster[] = $cell->innertext;
    }
    foreach($row->find('th') as $cell) {
        $roster[] = $cell->innertext;
    }
        $rowData[] = $roster;
    }

        foreach ($rowData as $row => $tr) {
            echo '<tr>';
            foreach ($tr as $td)
            echo '<td>' . $td .'</td>';
            echo '</tr>';
        }
        echo '</table></td><td>';
php html-table html-parsing simple-html-dom skip

评论


答:

1赞 u_mulder 4/10/2018 #1

您可以简单地从结果数组中弹出两个项目:find

$rows = $table->find('tr');
array_pop($rows);
array_pop($rows);

foreach ($rows as $row) {
    // do stuff here
}

当然,这不是一个理想的解决方案,作为替代方案,您可以获取找到的行并使用索引来控制当前元素:countforeach

$rows = $table->find('tr');
$limit = count($rows) - 2;
$counter = 0;

foreach ($rows as $row) {
    if ($counter++ < $limit) {
        break;
    }

    // do stuff
}

评论

0赞 Chris 4/11/2018
谢谢。使用并按愿交付。反之亦然,它将如何工作?假设我只想显示最后两行并跳过之前的所有行。array_pop
0赞 u_mulder 4/11/2018
使用计数器,如第二个示例所示。或者返回你弹出的元素,所以你可以它们和输出。array_poppop