【问题标题】:loop through html table and get tr, th and td in php with simple dom parser循环遍历 html 表并使用简单的 dom 解析器在 php 中获取 tr、th 和 td
【发布时间】:2019-06-05 15:50:22
【问题描述】:

我需要用简单的 html dom 解析器获取一个表,清理它(删除 attr 和空格),然后再次输出。

我的问题是,我如何使用 PHP 循环并以一个顺序输出 TH 和 TD? 目前它会将 TH 作为 TD 处理,但我希望正确设置 TH。

<table>
    <tbody>
        <tr>
            <th>Date1</th>
            <th>Date2</th>
        </tr>
        <tr>
            <td>01.01.2019</td>
            <td>05.01.2019</td>
        </tr>
    </tbody>
</table>
require('simple_html_dom.php');
$html = file_get_html( "template.html" );
$table = $html->find('table', 0);
$rowData = array();

foreach($table->find('tr') as $row) {
    $keeper = array();

    foreach($row->find('td, th') as $cell) {
        $keeper[] = $cell->plaintext;
    }
    $rowData[] = $keeper;
}

echo '<table">';
foreach ($rowData as $row => $tr) {
    echo '<tr>'; 
    foreach ($tr as $td)
        echo '<td>' . $td .'</td>';
    echo '</tr>';
}
echo '</table>';

我用 foreach 尝试了一些东西,但我认为我需要其他东西。

你的想法。

问候;s

【问题讨论】:

  • 只用Tidy?
  • 我不明白这个问题 - “我用 foreach 尝试了一些东西,但我想我需要其他东西。” 你尝试了 foreach,但没有用显然,你需要别的东西。什么没用?还有什么像什么?

标签: php html html-table simpledom


【解决方案1】:

您需要存储单元格的类型,将它们存储在行级别就足够了,因为它们应该都是相同的。然后在重建行时,使用此类型作为单元格类型来创建...

foreach($table->find('tr') as $row) {
    $keeper = array();

    foreach($row->find('td, th') as $cell) {
        $keeper[] = $cell->plaintext;
    }
    // Type is the 2nd & 3rd chars of html - <th>content</th> gives th
    // Store type and cell data as two elements of the rowData
    $rowData[] = ["type" => substr($cell,1,2), "cells" => $keeper];
}

echo '<table>';
foreach ($rowData as $row => $tr) {
    echo '<tr>';
    // Loop over the cells of the row
    foreach ($tr["cells"] as $td)
        // Output row type as the element type
        echo "<$tr[type]>" . $td ."</$tr[type]>";
        echo '</tr>';
}
echo '</table>';

【讨论】:

    【解决方案2】:

    你可以这样做:

    require('simple_html_dom.php');
    $html = file_get_html( "template.html" );
    $table = $html->find('table', 0);
    $rowData = array();
    
    foreach($table->find('tr') as $row) {
        $keeper = array();
    
        foreach($row->find('td, th') as $cell) {
            $data = array();
            $data['tag'] = $cell->tag;                      //stored Tag and Plain Text
            $data['plaintext'] = $cell->plaintext;
            $keeper[] = $data;
        }
        $rowData[] = $keeper;
    }
    
    echo '<table>';
    foreach ($rowData as $row => $tr) {
        echo '<tr>'; 
        foreach ($tr as $td)
            echo '<'.$td['tag'].'>' . $td['plaintext'] .'</'.$td['tag'].'>';  // Tag used
        echo '</tr>';
    }
    echo '</table>';
    

    【讨论】:

    • 你的投资,这真是太好了!
    猜你喜欢
    • 2019-03-04
    • 2012-11-06
    • 2018-03-05
    • 2012-12-24
    • 1970-01-01
    • 2015-09-30
    • 2020-04-18
    • 2020-10-24
    相关资源
    最近更新 更多