How to parse HTML table using PHP?

How to parse HTML table using PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Parse HTML Tables in PHP

Parsing raw HTML tables in PHP requires moving beyond simple string manipulation into a realm where understanding the Document Object Model (DOM) is essential. When you need to extract specific data, such as the second column of a table, treating the HTML as a linear block of text is fragile and prone to errors caused by nested tags or inconsistent whitespace. The robust approach involves utilizing PHP's built-in DOMDocument class or its simpler counterpart, SimpleXML, depending on the complexity of your markup.

To begin fetching data from a table, you must first instantiate a parser that can handle the non-sequential nature of HTML. Using DOMDocument offers the most control and is the standard for complex scraping tasks. You load your HTML string into this object using the loadHTML() method. Note that loadHTML() accepts an optional third argument to specify the encoding; if you are dealing with UTF-8 content, explicitly setting it prevents character set issues later in the process.

Once the document is loaded, navigating to the table structure involves querying the DOM for <table> elements. If your page contains multiple tables, you might need to filter them based on specific attributes or simply iterate through all of them. For a single-column extraction task like getting the second column, you typically loop through the rows (<tr>) and then access the cells within those rows.

Consider the following implementation using DOMDocument:

$html = '<table><tr><td>A</td><td>B</td><td>C</td></tr><tr><td>D</td><td>E</td><td>F</td></tr></table>';

$dom = new DOMDocument();
// Suppress warnings for malformed HTML often found in scraped content
libxml_use_internal_errors(true); 
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();

$tables = $dom->getElementsByTagName('table');
if ($tables->length > 0) {
    $table = $tables[0];
    $rows = $table->getElementsByTagName('tr');
    
    foreach ($rows as $row) {
        // Get all cells in the row, including header cells if present
        $cells = $row->getElementsByTagName('td');
        
        if ($cells->length >= 2) {
            // Access the second column (index 1)
            echo $cells[1]->textContent . PHP_EOL;
        }
    }
}

A critical detail often overlooked is handling cells that are not strictly <td> tags. In many tables, header rows use <th> tags instead. If you strictly query for td elements, you might skip the first column of a header row entirely, shifting your index and causing data misalignment. To ensure accuracy regardless of whether a cell is a data cell or a header cell, it is often safer to query for all cells in the row using a generic selector logic or by checking both tag names dynamically.

Another approach that simplifies this syntax significantly is SimpleXML. While DOMDocument provides more granular control over DOM events and node manipulation, SimpleXML offers a cleaner, XML-like interface that can be less verbose for straightforward extraction tasks. You load the HTML similarly, but then cast it to a SimpleXML object or use its built-in methods. This is particularly useful when you want to avoid the boilerplate of setting up DOM exceptions or managing node lists manually.

However, be cautious when relying on these libraries if your source HTML contains malformed tags or unclosed elements. While modern parsers are forgiving, they do not always correct structural errors silently without potentially altering the document tree in ways that affect your indices. Always validate that the table structure matches expectations before assuming the second column is indeed the data you expect.

For projects built on the Laravel framework, there are additional considerations regarding how to handle such parsing within your application's architecture. While raw DOM parsing works well for one-off scripts, integrating it into a larger system might benefit from using packages that specialize in HTML scraping and normalization, ensuring consistency across different views of your data.

Our network