How can PHP be used to delete existing data in a text file before writing new data?

To delete existing data in a text file before writing new data, you can open the file in write mode, which will clear the existing content. Then, you can write the new data to the file. This approach ensures that the file is empty before writing the new data.

$file = 'data.txt';

// Open the file in write mode to clear existing content
$fp = fopen($file, 'w');

// Write new data to the file
fwrite($fp, 'New data to be written');

// Close the file
fclose($fp);