Search code examples
phpregexhtml-parsing

Parse MSHTML and extract a <table> and it's contents


I just can't seem to work out how to pull the entire table from a page using regex.

This is my PHP:

$printable = file_get_contents('http://entertainment.soundboxaudio.com/testplaylist.htm');
$array = array();
preg_match( '/<TABLE>(.*?)<\/TABLE>/si', $printable, $array ) ;
$findit = "$array[1]";
echo("$findit");

Solution

  • Here we go again... do NOT use regex to extract HTML. HTML is not a regular language and cannot be reliably analyzed with a regex. Use DOM instead.

    $printable = file_get_conttents('...');
    $dom = new DOMDocument;
    $dom->loadHTML($printable);
    $xpath = new DOMXpath($dom);
    
    $tables = $xpath->query("//table");
    
    $table_html = array();
    
    foreach($tables as $table) { // workaround for PHP DOM not support innerHTML
       $temp = new DOMDocument;
       $temp->appendChild($temp->importNode($table, true));
       $table_html[] = trim($temp->saveHTML());
    }
    

    As well, surrounding variables you're echoing is just a waste of a string operation

    echo $x
    echo "$x";
    

    work identically, except the quoted version wastes some cpu produce a temporary string that only gets thrown away again.