How can fopen() be used in PHP to clear the contents of a file before writing new data to it?

To clear the contents of a file before writing new data to it using fopen() in PHP, you can open the file in "w" mode, which truncates the file to zero length before writing. This effectively clears the file before new data is written to it.

$file = 'example.txt';

$handle = fopen($file, 'w');
fclose($handle);

// Now you can write new data to the file
$newData = "This is new data.";
file_put_contents($file, $newData);