Converting HTML Table to a CSV automatically using PHP?

Converting HTML Table to a CSV automatically using PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

Parsing HTML Tables to Generate CSV Files in PHP

Converting an HTML table structure into a CSV file is a common requirement when exporting data from legacy systems or dynamic web pages. While manual copy-pasting works for one-off tasks, automating this process in PHP requires parsing the DOM and restructuring the output format. The goal is to transform nested tags like <table>, <tr>, <th>, and <td> into a flat, delimiter-separated text file that can be easily opened by spreadsheet applications.

To achieve this, you need to parse the HTML string into a Document Object Model (DOM) structure. PHP provides the DOMDocument class for this purpose, though it is not always as forgiving with raw HTML strings as a browser parser. You often need to load the content with error handling enabled and potentially sanitize the string before parsing. Once the DOM is loaded, you can iterate through the table rows (<tr>) and their respective cells (<th> or <td>).

The core logic involves looping through these nodes, extracting the text content, and appending it to a file handle. The output format must strictly adhere to CSV standards: fields containing commas, quotes, or newlines must be enclosed in double quotes, and internal quotes must be escaped by doubling them. A naive approach that simply concatenates nodeValue without checking for special characters will result in malformed data that spreadsheet software cannot read correctly.

Here is a functional approach using the DOMDocument class to handle the conversion:

$tableHtml = '<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>';

// Remove whitespace and load into DOMDocument
$tableHtml = preg_replace('/\s+/', ' ', $tableHtml);
$dom = new DOMDocument();
@$dom->loadHTML($tableHtml, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$outputPath = '/test/home/path_to_csv';

if (file_exists($outputPath)) {
    chmod($outputPath, 0777);
}

$handle = fopen($outputPath, 'w');

// Iterate through rows and cells
$rows = $dom->getElementsByTagName('tr');
foreach ($rows as $row) {
    $cells = $row->getElementsByTagName('th') ?? $row->getElementsByTagName('td');
    
    // Collect cell values from either header or data cells
    $values = [];
    foreach ($cells as $cell) {
        $values[] = trim($cell->nodeValue);
    }

    // Escape CSV fields containing special characters
    $safeValues = array_map(function($val) {
        if (strpos($val, ',') !== false || strpos($val, '"') !== false || strpos($val, "\n") !== false) {
            return '"' . str_replace('"', '""', $val) . '"';
        }
        return $val;
    }, $values);

    fputcsv($handle, $safeValues);
}

fclose($handle);

In this implementation, we first normalize the whitespace to ensure the DOM parser doesn't choke on formatting. We then iterate through each <tr> element. A critical detail is handling both header cells (<th>) and data cells (<td>). Sometimes tables mix these, so checking for available tags or iterating over all child elements that contain text is a safer strategy than assuming a specific tag order.

The fputcsv() function handles the delimiter logic internally, but we must preprocess the strings to ensure they don't break the CSV format. If a cell contains "row 1, cell 1", simply writing it to the file without quotes will cause the parser to split that single row into two columns. The code snippet above demonstrates how to detect commas and double quotes, wrapping the value in quotes and escaping internal quotes as per RFC 4180 standards.

Performance and Scalability Considerations

While DOMDocument is robust, it can be memory-intensive for very large tables. For massive datasets, streaming parsers or regular expressions might offer better performance, though they lack the flexibility of a DOM tree. Another trade-off is the handling of complex HTML attributes; if your table includes inline styles or nested tables, you may need to strip those attributes before extraction to avoid parsing errors.

If you are building this feature within a larger application stack, consider whether an existing package handles edge cases like empty cells or malformed HTML better than a custom script. Libraries such as html-parser or similar tools can sometimes simplify the extraction logic by providing higher-level abstractions.

For projects already using the Laravel framework, the underlying engine handles much of the heavy lifting regarding file permissions and path resolution, making it straightforward to place the generated CSV in /test/home/path_to_csv without worrying about manual permission adjustments. However, always ensure the target directory exists and is writable before attempting to create the file.

Ultimately, the choice between a custom DOMDocument script and a third-party library depends on the complexity of your HTML input and the performance constraints of your server environment.

Our network