dcarbone/table-mapper

复杂的HTML解析助手

1.1.1 2014-04-29 13:55 UTC

This package is auto-updated.

Last update: 2024-09-17 09:43:36 UTC


README

TableMapper 是一个类,我编写它来简化复杂HTML表的消费。

示例:

<table>
    <tbody>
        <tr>
            <td colspan="3">Row 0 : Cell 0</td>
            <td rowspan="2">Row 0 : Cell 1</td>
        </tr>
        <tr>
            <td>Row 1 : Cell 0</td>
            <td>Row 1 : Cell 1</td>
            <td>Row 1 : Cell 2</td>
        </tr>
    </tbody>
</table>

看起来像这样

然而,这可能有点棘手。因此,这个类会克隆你传入的表格元素,并创建一个内存中的版本,看起来像这样

<table>
    <tbody>
        <tr>
            <td>Row 0 : Cell 0</td>
            <td>Row 0 : Cell 0</td>
            <td>Row 0 : Cell 0</td>
            <td>Row 0 : Cell 1</td>
        </tr>
        <tr>
            <td>Row 1 : Cell 0</td>
            <td>Row 1 : Cell 1</td>
            <td>Row 1 : Cell 2</td>
            <td>Row 0 : Cell 1</td>
        </tr>
    </tbody>
</table>

这看起来像这样

用法

$tableHTML = <<<HTML
<h1>Original Table</h1>

<table>
    <tbody>
        <tr>
            <td colspan="3">Row 0 : Cell 0</td>
            <td rowspan="2">Row 0 : Cell 1</td>
        </tr>
        <tr>
            <td>Row 1 : Cell 0</td>
            <td>Row 1 : Cell 1</td>
            <td>Row 1 : Cell 2</td>
        </tr>
    </tbody>
</table>
HTML;

$dom = new \DOMDocument;
$dom->loadHTML($tableHTML);

$tableMapper = new \DCarbone\TableMapper($dom->getElementsByTagName('table')->item(0));
$tableMapper->createMap();

$dom->appendChild($dom->createElement('h1', 'Parsed Table'));

$newTable = $dom->createElement('table');
$dom->appendChild($newTable);

foreach($tableMapper->getRowCellMap() as $groupi=>$groupDef)
{
    foreach($groupDef as $rowi=>$cellMap)
    {
        $newTr = $dom->createElement('tr');
        $newTable->appendChild($newTr);

        foreach($cellMap as $cellNum)
        {
            $cell = $tableMapper->getCell($groupi, $rowi, $cellNum);
            $newTr->appendChild($dom->createElement('td', $cell->nodeValue));
        }
    }
}

echo $dom->saveHTML();

这是一个非常简单的类。以下几点需要注意

  • TableMapper 不会修改你传入的 DOMElement,它会在进行任何操作之前克隆并导入到一个新的DOM中。
  • TableMapper 不会修复无效的HTML
  • TableMapper 不会帮你洗衣服。