【问题标题】:PHP Table Parsing Script Only Selects the First Table it SeesPHP 表解析脚本只选择它看到的第一个表
【发布时间】:2011-10-16 13:16:56
【问题描述】:

我正在使用 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;
}

【问题讨论】:

标签: php html html-table html-parsing


【解决方案1】:

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

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;
}

【讨论】:

  • 更新到 foreach() 循环,必须循环 $tablesMatches[0]。
【解决方案2】:

preg_match 命令会在找到第一个匹配项时自行停止,正如您稍后在代码中所做的那样,使用preg_match_all 并遍历所有匹配项。

【讨论】:

  • 我可以将每个表存储在一个单独的数组中
  • 当然,只需添加第三个参数 $tables 并对其进行迭代。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多