PHP表解析脚本仅选择它看到的第一个表

时间:2011-10-16 13:16:56

标签: php html html-table html-parsing

我正在使用PHP脚本将HTML表解析为数组。但是我遇到了一个问题,我正在尝试解析的页面在页面上有3个表,而脚本只选择它看到的第一个表。有没有什么方法可以让它解析它看到的每一张桌子或只是第三张桌子?

function parseTable($html)
{
    // Find the table
    preg_match("/<table.*?>.*?<\/[\s]*table>/s", $html, $table_html);

    // Get title for each row
    preg_match_all("/<th.*?>(.*?)<\/[\s]*th>/", $table_html[0], $matches);
    $row_headers = $matches[1];

    // Iterate each row
    preg_match_all("/<tr.*?>(.*?)<\/[\s]*tr>/s", $table_html[0], $matches);

    $table = array();

    foreach($matches[1] as $row_html)
    {
        preg_match_all("/<td.*?>(.*?)<\/[\s]*td>/", $row_html, $td_matches);
        $row = array();

        for($i=0; $i<count($td_matches[1]); $i++)
        {
            $td = strip_tags(html_entity_decode($td_matches[1][$i]));
            $row[$row_headers[$i]] = $td;
        }

        if(count($row) > 0)
        {
            $table[] = $row;
        }
    }

    return $table;
}

2 个答案:

答案 0 :(得分:0)

找到第一个匹配项时,

preg_match命令会自动停止,因为稍后在代码中使用preg_match_all并迭代所有匹配项。

答案 1 :(得分:0)

我认为这个函数的更新版本返回一个表数组:

function parseTable($html)
{
    // Find the table
    preg_match_all("/<table.*?>.*?<\/[\s]*table>/s", $html, $tablesMatches);
    $tables = array();
    foreach ($tablesMatches[0] as $table_html) {

        // Get title for each row
        preg_match_all("/<th.*?>(.*?)<\/[\s]*th>/", $table_html, $matches);
        $row_headers = $matches[1];

        // Iterate each row
        preg_match_all("/<tr.*?>(.*?)<\/[\s]*tr>/s", $table_html, $matches);

        $table = array();

        foreach ($matches[1] as $row_html)
        {
            preg_match_all("/<td.*?>(.*?)<\/[\s]*td>/", $row_html, $td_matches);
            $row = array();
            for ($i = 0; $i < count($td_matches[1]); $i++)
            {
                $td = strip_tags(html_entity_decode($td_matches[1][$i]));
                $row[$row_headers[$i]] = $td;
            }

            if (count($row) > 0)
                $table[] = $row;
        }

        $tables[] = $table;
    }

    return $tables;
}