Clearing content of text file using php

To clear the contents of a text file using PHP, you can use the file_put_contents() function. This function writes a string to a file. If the file does not exist, it will be created. If the file already exists, it will be truncated (its contents will be deleted).

Here is an example of how you would use the file_put_contents() function to clear the contents of a text file called "example.txt":


// Create an empty file named "example.txt"
file_put_contents('example.txt', '');

// Check if the file was created
if (file_exists('example.txt')) {
  echo "Empty file created successfully.";
} else {
  echo "Failed to create empty file.";

This will clear the contents of "example.txt" and will write an empty string to the file.

You can also use fopen, ftruncate and fclose to clear the contents of a text file


// Open the file for writing and truncate its content
$file = fopen('example.txt', 'w');
ftruncate($file, 0);

// Check if the file was truncated
if (filesize('example.txt') === 0) {
  echo "File truncated successfully.";
} else {
  echo "Failed to truncate file.";

This will open the file in "write" mode, truncate it to zero bytes and close it.