What are some best practices for reading and displaying data from a text file using PHP?

When reading and displaying data from a text file using PHP, it is important to properly handle file opening, reading, and closing operations. It is also essential to sanitize and validate the data before displaying it to prevent any security vulnerabilities.

<?php
// Open the text file for reading
$filename = "data.txt";
$file = fopen($filename, "r");

// Read and display each line of the file
if ($file) {
    while (($line = fgets($file)) !== false) {
        // Sanitize and validate the data before displaying
        $data = htmlspecialchars($line);
        echo $data . "<br>";
    }
    fclose($file);
} else {
    echo "Error opening the file.";
}
?>