Search code examples
phpfwrite

How to clear a text file ready for fwrite


I have a text file that is being written with fwrite, how would I delete all the contents of this text file so that I can write onto it a fresh. I've tried to find another function but with no luck.

Example code I am using, I want to clear it before I enter this information:

$string = ', {"key": "'.$info['Name'].'", "value": "'.$info['Name'].'"}';
    $fp = fopen('data_old.txt', 'a');
    fwrite($fp, $string);
    fclose($fp);

Solution

  • If you look at the PHP documentation for fopen, you will see the list of "modes" available in the second parameter. You are passing "a" which means append. You want to pass "w" which means "write".

    'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

    'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.