What are the best practices for handling HTML context when generating tables from text files in PHP?

When generating tables from text files in PHP, it is important to properly handle HTML context to prevent any potential security vulnerabilities such as cross-site scripting (XSS) attacks. One way to do this is by using the htmlspecialchars() function to escape any special characters in the text before outputting it as HTML.

<?php
// Read text file content
$text = file_get_contents('data.txt');

// Split text into rows
$rows = explode("\n", $text);

// Start HTML table
echo '<table>';

// Loop through rows and create table rows
foreach ($rows as $row) {
    echo '<tr>';
    $columns = explode(',', $row);
    foreach ($columns as $column) {
        echo '<td>' . htmlspecialchars($column) . '</td>';
    }
    echo '</tr>';
}

// End HTML table
echo '</table>';
?>