How to clear a text file ready for fwrite

18,485

Solution 1

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.

Solution 2

You can change your mode parameter in fopen:

$fp = fopen('data_old.txt', 'w+');

By the way, I used w+ in case you want to read from it as well, for just writing you can use w.

Solution 3

Use the w option instead of the a option in fopen.

like fopen('file.txt','w');

this puts the pointer at the beginning of the file instead of the end

http://php.net/manual/en/function.fopen.php

Share:
18,485
MattHeywood
Author by

MattHeywood

Updated on August 30, 2022

Comments

  • MattHeywood
    MattHeywood over 1 year

    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);