0

I'm using a PHP script to parse a HTML table into an array. But I'm running into an issue, the page I'm trying to parse has 3 tables on the page, and the script only selects the first table it sees. Is there any way I could make it so it will parse every table it sees or just the 3rd table?

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;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Shane
  • 23
  • 2
  • 9
  • 4
    Use preg_match_all() for your table matching expression, like you are already doing for the headers, rows and cells. – Jan-Henk Oct 16 '11 at 13:18
  • Possible duplicate of [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Brian Tompsett - 汤莱恩 Jun 30 '17 at 10:28

2 Answers2

0

preg_match command stops itself when the first occurrence is found, as you do later in the code use the preg_match_all and iterate over all the matches.

Gianpaolo Di Nino
  • 1,139
  • 5
  • 17
0

I think this updated version of your function returns an array of tables:

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;
}
Jan-Henk
  • 4,864
  • 1
  • 24
  • 38