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