What is the best practice for handling file creation and writing in PHP to avoid errors like "file not found"?

When creating and writing files in PHP, it is important to check if the file exists before attempting to write to it to avoid errors like "file not found". One way to handle this is by using the `file_exists()` function to check if the file exists before proceeding with the file writing operation.

$file_path = 'example.txt';

if (file_exists($file_path)) {
    $file = fopen($file_path, 'w');
    fwrite($file, 'Hello, World!');
    fclose($file);
    echo 'File created and written successfully.';
} else {
    echo 'File not found.';
}