Can fopen() with the 'w+' mode be used to clear the contents of a .txt file in PHP without unlinking it first?

Yes, you can use fopen() with the 'w+' mode to clear the contents of a .txt file in PHP without unlinking it first. When you open a file in 'w+' mode, it truncates the file to zero length if it exists or creates a new file if it doesn't exist. This effectively clears the contents of the file while keeping the file itself intact.

$file = 'example.txt';
$handle = fopen($file, 'w+');
fclose($handle);