[英]Using preg_match_all to parse a html table with PHP
我使用以下PHP腳本來解析表。
如果每個元素位於同一行,則它可以工作,例如:
<td></td>
<td></td>
<td></td>
如果“開始標記”和“關閉標記”在不同的行上,我該如何使其工作? 像這樣:
<td></td>
<td>
</td>
<td></td>
PHP腳本:
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;
}
Preg_match不用於解析HTML,因為它不是正則表達式。 最好的解決方案是使用
XML解析器 - PHP Doc
每個工具都有其要解決的問題,解析不是preg_match的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.