What are some best practices for handling file operations in PHP to ensure correct data output?

When handling file operations in PHP, it is important to always check for errors and handle them appropriately to ensure correct data output. This includes checking if the file exists before reading from or writing to it, closing the file after operations are completed, and using error handling mechanisms such as try-catch blocks to handle exceptions.

// Check if the file exists before reading from it
$file = 'example.txt';
if (file_exists($file)) {
    $handle = fopen($file, 'r');
    if ($handle) {
        $data = fread($handle, filesize($file));
        fclose($handle);
        echo $data;
    } else {
        echo 'Error opening file.';
    }
} else {
    echo 'File does not exist.';
}