0

我需要用简单的 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

4

2 回答 2

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>';
于 2019-01-10T18:45:35.710 回答
1

你可以这样做:

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-01-10T18:57:16.807 回答