You can use the file_put_contents
function to manipulate a file.
Creating a TXT File
file_put_contents
can be used to create a file with a certain content.
Example:
$filename = __DIR__ . '/arquivos/log.txt';
file_put_contents($filename, 'meu conteúdo');
The above example will cause the log.txt
file to be created within the arquivos
folder of the current directory of your script, defined by the magic constant __DIR__
.
However, in this example, the file will be overwritten if it exists. And with each new request, it will always change the content.
Adding data to the end of a TXT file
If you want to always add new content at the end of the file, you can use the FILE_APPEND
flag as the file_put_contents
parameter.
So:
file_put_contents($filename, 'meu conteúdo', FILE_APPEND);
This will always create new content at the end of the file.
Why not use CSV?
As in your example it seems to me that you are working with data with specific organized structures, I would use a CSV.
PHP handles the CSV very well.
Take a look at these explanations of the PHP Manual:
fgetcsv
fputcsv
data serialization
From the serialize
and unserialize
functions of PHP you can "save" variable values to later retrieve them. All you need is a file where you save this data.
See an example.
Saving the data:
$serial = serialize($_POST);
file_put_contents('serial.txt', $serial);
Retrieving data:
$dados = unserialize(file_get_contents('serial.txt'));
print_r($dados); // Dados anterioremente salvos vindos de $_POST
It seems to me that internally PHP uses these functions to save / retrieve session data ( $_SESSION
).