简体   繁体   中英

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

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.

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 .

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

To overwrite an existing file use the write only mode with fopen, which will open the file for writing and set the point to the beginning of the file and also truncate the file to zero length:

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

You can do this another way

$file_destination = "./your_text_file_name.txt";
unlink($file_destination);
$your_data = "ABCabc";
$handle = fopen ($file_destination, "a+");
fputs($handle, $your_data);
fclose($handle);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM