How can the efficiency of PHP code be improved when processing and displaying data from a text file in a table format?

When processing and displaying data from a text file in a table format using PHP, efficiency can be improved by minimizing file reads and utilizing caching mechanisms. One way to achieve this is by reading the file contents once, storing them in an array or object, and then using that data to generate the table. Additionally, using functions like file_get_contents() instead of fopen() and fgets() can simplify the code and improve performance.

<?php

// Read the contents of the text file into an array
$data = file('data.txt', FILE_IGNORE_NEW_LINES);

// Generate the table header
echo '<table>';
echo '<tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>';

// Loop through the data array to display each row in the table
foreach ($data as $row) {
    $columns = explode(',', $row);
    echo '<tr>';
    foreach ($columns as $column) {
        echo '<td>' . $column . '</td>';
    }
    echo '</tr>';
}

echo '</table>';

?>