What are the best practices for handling and manipulating text files in PHP?

When handling and manipulating text files in PHP, it is important to use the appropriate functions to read, write, and manipulate the contents of the file. Some best practices include using file handling functions like fopen, fread, fwrite, and fclose, as well as using proper error handling techniques to ensure the file operations are successful.

// Example of reading a text file line by line
$filename = 'example.txt';
$handle = fopen($filename, 'r');

if ($handle) {
    while (($line = fgets($handle)) !== false) {
        echo $line;
    }
    fclose($handle);
} else {
    echo 'Error opening the file';
}