Jason Storey
Jason Storey

Reputation: 469

php cannot write new line, file gets overwirtten

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

Answers (3)

Funk Forty Niner
Funk Forty Niner

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

Si8
Si8

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

John Conde
John Conde

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

Related Questions