You can use the function file_put_contents
to manipulate a file.
Creating a TXT file
The 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 create the file log.txt
inside the briefcase arquivos
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 at the end of a TXT file
If you always want to add new content at the end of the file, you can use the flag FILE_APPEND
as a parameter of file_put_contents
.
Thus:
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 CSV very well.
Take a look at these explanations from the PHP Handbook:
fgetcsv
fputcsv
data serialization
From the office serialize
and unserialize
PHP’s can "save" variable values to later retrieve them. All you need is a file where to save this data.
Take an example.
Saving the data:
$serial = serialize($_POST);
file_put_contents('serial.txt', $serial);
Retrieving the 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/recover session data ($_SESSION
).
Yes, it is possible. See functions
fopen
,file_put_contents
,fread
,fwrite
(the same as the C language). They will help you.– Vinícius Gobbo A. de Oliveira