Reputation: 469
I have read a lot of questions, none of which worked. I have a txt file. The first line contains headers separated by a tab "\n". Now when i post to this file I want it to take the values and separate them by a tab and then write them on a new line of the txt file. But when I run it, it just overwrites the first line.
<?php
$post = $_POST;
$myFile = 'test.txt';
$fh = fopen($myFile, 'w');
$columns = "";
foreach ($post as $key => $value){
$columns .= $value . "\t";
}
fwrite($fh, $columns . PHP_EOL);
fclose($fh);
?>
Upvotes: 0
Views: 323
Reputation: 74217
Try $fh = fopen($myFile, 'a');
if you don't want to overwrite content.
Using w
overwrites, while a
or a+
appends.
For more information on the fwrite()
function, you can consult the PHP manual.
Also consult the PHP manual on fopen()
http://php.net/manual/en/function.fopen.php
'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.
'a+'
Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
Upvotes: 0
Reputation: 9225
w
is used for writing which means anything before gets overwritten.
Change the following line:
$fh = fopen($myFile, 'w'); //w = write
To
$fh = fopen($myFile, 'a'); //a = append
It should fix the issue for you.
Upvotes: 0
Reputation: 219824
You're looking for a
instead w
:
$fh = fopen($myFile, 'a');
From the docs:
'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.
'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.
Upvotes: 1