我使用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;
}
我认为这个更新版本的函数返回一个表数组:
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;
}
preg_match
命令在找到第一个匹配项时自动停止,正如您稍后在代码中使用preg_match_all
并遍历所有匹配项所做的那样。