Сценарий синтаксического анализа таблицы PHP выбирает только первую таблицу, которую видит - PullRequest
0 голосов
/ 16 октября 2011

Я использую скрипт PHP для разбора таблицы HTML в массив. Но я столкнулся с проблемой: на странице, которую я пытаюсь проанализировать, есть 3 таблицы на странице, и сценарий выбирает только первую таблицу, которую видит. Можно ли как-нибудь сделать так, чтобы он анализировал все таблицы, которые он видит, или только 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;
}

Ответы [ 2 ]

0 голосов
/ 16 октября 2011

Я думаю, что эта обновленная версия вашей функции возвращает массив таблиц:

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;
}
0 голосов
/ 16 октября 2011
Команда

preg_match останавливается сама при обнаружении первого вхождения, как вы позже сделаете в коде, используя preg_match_all и перебирая все совпадения.

...