Add data to a txt file

Asked

Viewed 1,461 times

3

I have the following code:

$msg = "teste";
$myfile = fopen("lista.txt", "w");
fwrite($myfile, $msg."\n");
fclose($myfile);

If I change the variable value $msg it opens the file deletes the $msg and replaces it with the new value. How can I keep both?

Example of how I want the output inside the file txt:

teste 
novo valor
  • 1

    See the possible ways to open a file and what are the differences between them.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

2 answers

6

You must open the file to add and not to write:

$msg = "teste";
$myfile = fopen("lista.txt", "a");
fwrite($myfile, $msg."\n");
fclose($myfile);

I put in the Github for future reference.

At least that’s the simplest way if that’s all you want. If you want to do multiple operations then you need a slightly more sophisticated algorithm to manage file placement.

Another possibility is to use the file_put_contents() with the argument FILE_APPEND, thus avoids control of files.

Documentations:

5

The function file_put_contents can be used to do this in a simpler way. According to the PHP documentation, this function is the same thing as calling fopen, fwrite and fclose functions:

This Function is identical to Calling fopen(), fwrite() and fclose() successively to write data to a file.

That is, this function serves as a simplified way to write data in a file.

$msg = 'teste' . PHP_EOL;
file_put_contents('lista.txt', $msg, FILE_APPEND);

The constant FILE_APPEND serves to add a new content without deleting the existing one. Therefore, if the function is executed again with a different value, the value "teste" will not be erased.

PS: Remembering that constant PHP_EOL serves to add a line break (independent of the operating system).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.