How can PHP developers ensure proper context switching and data formatting when dynamically generating HTML tables from database results?

When dynamically generating HTML tables from database results in PHP, developers should ensure proper context switching and data formatting by using PHP's built-in functions like htmlspecialchars() to escape special characters and prevent XSS attacks. Additionally, developers should properly format data retrieved from the database before outputting it in the HTML table to ensure consistent display and prevent any potential security vulnerabilities.

<?php
// Assume $results is an array of database results
echo '<table>';
foreach ($results as $row) {
    echo '<tr>';
    foreach ($row as $value) {
        echo '<td>' . htmlspecialchars($value) . '</td>';
    }
    echo '</tr>';
}
echo '</table>';
?>