Adding data to a txt file

3

I have the following code:

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

If I change the value of the variable $msg it opens the file deletes the $msg previous 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
    
asked by anonymous 08.10.2018 / 21:34

2 answers

6

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

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

At least this is the simplest form if you just want it. If you want to do multiple operations then you need a slightly more sophisticated algorithm to manage the positioning in the file.

Another possibility is to use file_put_contents() with argument FILE_APPEND , thus avoiding file control.

Documentation:

08.10.2018 / 21:42
5

The file_put_contents function can be used to do this in a simpler way. According to the PHP documentation, this function is the same as calling the 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 of writing data to a file.

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

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

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

    
08.10.2018 / 22:41