Reputation: 3763
I use the following PHP script to parse a table.
It works if each element is on the same row, for example:
<td></td>
<td></td>
<td></td>
How can I make it work if "start tag" and "close tag" are on different rows? Like so:
<td></td>
<td>
</td>
<td></td>
PHP script:
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;
}
Upvotes: 0
Views: 6656
Reputation: 850
Preg_match is not made to parse HTML since it's not a regular expression. The best solution is to use an
XML Parser - PHP Doc
Each tool has its problem to solve and parsing is not preg_match's one
Upvotes: 2