Using preg_match_all to parse a html table with PHP
<p>I use the following PHP script to parse a table.</p>

<p>It works if each element is on the same row, for example:</p>

<pre><code>&lt;td&gt;&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
</code></pre>

<p>How can I make it work if "start tag" and "close tag" are on different rows? Like so:</p>

<pre><code>&lt;td&gt;&lt;/td&gt;
&lt;td&gt;
&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
</code></pre>

<p><strong>PHP script:</strong></p>

<pre><code>function parseTable($html)
{
  // Find the table
  preg_match("/&lt;table.*?&gt;.*?&lt;\/[\s]*table&gt;/s", $html, $table_html);

  // Get title for each row
  preg_match_all("/&lt;th.*?&gt;(.*?)&lt;\/[\s]*th&gt;/", $table_html[0], $matches);
  $row_headers = $matches[1];

  // Iterate each row
  preg_match_all("/&lt;tr.*?&gt;(.*?)&lt;\/[\s]*tr&gt;/s", $table_html[0], $matches);

  $table = array();

  foreach($matches[1] as $row_html)
  {
    preg_match_all("/&lt;td.*?&gt;(.*?)&lt;\/[\s]*td&gt;/", $row_html, $td_matches);
    $row = array();
    for($i=0; $i&lt;count($td_matches[1]); $i++)
    {
      $td = strip_tags(html_entity_decode($td_matches[1][$i]));
      $row[$row_headers[$i]] = $td;
    }

    if(count($row) &gt; 0)
      $table[] = $row;
  }
  return $table;
}
</code></pre>
