how to create html table in php

how to create html table in php

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

Stefan Bogdanescu

Founder & Senior Architect

Transforming Raw CSV-Like Data into Dynamic HTML Tables in PHP

Converting raw text data into a structured web interface is a frequent requirement when building dashboards or admin panels. The snippet you provided demonstrates a common starting point: reading a file line-by-line and using explode to parse simple delimiter-separated values. While that approach works for basic output, it lacks the structure needed to render an HTML table dynamically.

To achieve the desired layout where headers align with data rows, you need to separate the parsing logic from the rendering logic. The core challenge here is that your current loop outputs three separate echo statements per line. This results in raw text interleaved with newlines rather than a grid structure. To fix this, you must collect the parsed segments into an array for each row before generating the HTML tags.

Here is a robust approach using PHP's fgetcsv or manual string manipulation to build the table structure. If your delimiter is strictly a semicolon (;) and there are no embedded commas within the data fields, you can stick with explode. However, if the data might contain semicolons inside quoted strings (e.g., /path/to/file;name.txt), switching to a CSV parser library or fgetcsv would be safer. Assuming your prod.txt format is rigid and safe for explode, here is how you refactor the logic:

<?php
$file = 'prod.txt';
$data = [];

// Read the file into an array of lines
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($lines as $line) {
    // Split the line by the semicolon delimiter
    $pieces = explode(';', $line);

    // Validate that we have exactly 4 pieces (header + 3 data fields based on your example)
    // Adjust indices based on actual field count. Your example shows 3 parts per line.
    if (count($pieces) >= 4) { 
        // Assuming the format is PREFIX;PART;FILE;[optional extra]
        $row = [
            'prefix' => trim($pieces[0]),
            'part'   => trim($pieces[1]),
            'file'   => trim($pieces[2])
        ];

        $data[] = $row;
    }
}

// Now iterate through the collected data to build the HTML table
echo '<table border="1" cellpadding="8">';
echo '<tr><th>PREFIX</th><th>PART</th><th>FILE</th></tr>';

foreach ($data as $row) {
    echo '<tr>';
    echo '<td>' . htmlspecialchars($row['prefix']) . '</td>';
    echo '<td>' . htmlspecialchars($row['part']) . '</td>';
    echo '<td>' . htmlspecialchars($row['file']) . '</td>';
    echo '</tr>';
}

echo '</table>';
?>

The critical shift here is moving from immediate echoing to accumulating data in a $data array. Once the loop completes, you iterate through that clean array to generate <tr> and <td> elements. This separation ensures that if your source file changes or grows, the HTML generation logic remains decoupled from the parsing logic.

Security is another vital consideration when rendering dynamic tables. Your source data comes from a text file, which could theoretically contain user-generated content or malicious scripts if this file is populated by external input. Always wrap your output strings in htmlspecialchars() before echoing them into an HTML context. This prevents Cross-Site Scripting (XSS) vulnerabilities by converting special characters like <, >, and & into their HTML entity equivalents, ensuring that the browser renders the text as data rather than executable code.

Performance-wise, loading the entire file into memory via file() is acceptable for small to medium datasets. If you are processing gigabytes of log files where memory is a constraint, you would switch to reading the file pointer line-by-line using fgets() instead. For larger projects or if you need more advanced data manipulation features like automatic escaping, header handling, and pagination, consider adopting a framework like Laravel. The ecosystem surrounding such tools often provides elegant abstractions for rendering tables without reinventing the wheel.

Ultimately, the goal is to move away from procedural string concatenation toward structured data handling. By parsing the data first and then mapping it to HTML elements, you create maintainable code that scales better as your requirements evolve.

Our network