萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 將 HTML 表格轉為多維陣列實現資料採集

透過正則移除 <table>、<tr>、<td> 標籤,以自定義分隔符 {tr}、{td} 替換結尾標籤,再分割重組為「行 → 列」二維陣列。

核心函數

function get_td_array(string $table): array {
    $table = preg_replace('~<table[^>]*>~si', '', $table);
    $table = preg_replace('~<tr[^>]*>~si', '', $table);
    $table = preg_replace('~<td[^>]*>~si', '', $table);
    $table = str_replace('</tr>', '{tr}', $table);
    $table = str_replace('</td>', '{td}', $table);
    $table = preg_replace('~<[/!]*?[^<>]*>~si', '', $table); // 清除殘留標籤
    $table = preg_replace('~(\r\n|\n|\r)[\s]+~', '', $table);    // 清除空白行
    $table = str_replace([' ', ' '], '', $table);           // 清除空格

    $rows = explode('{tr}', $table);
    array_pop($rows); // 最後一個空元素

    $result = [];
    foreach ($rows as $row) {
        $cols = explode('{td}', $row);
        array_pop($cols);
        $result[] = $cols;
    }
    return $result;
}

使用範例

$html = '<table><tr><td>A1</td><td>B1</td></tr><tr><td>A2</td><td>B2</td></tr></table>';
$data = get_td_array($html);
/*
Array
(
    [0] => Array ( [0] => A1, [1] => B1 )
    [1] => Array ( [0] => A2, [1] => B2 )
)
*/

局限與改進

  • 巢狀表格、合併儲存格(rowspan/colspan)無法正確處理。
  • 建議改用 DOMDocument + DOMXPath 遍歷 //table//tr 並逐格 td/text() 解析,語義正確且健壯。
copyright © 萬盛學電腦網 all rights reserved