.txt File Handling

1

I have a page in php called "badge.php", and a .txt file called "badge.txt". In this .txt file, this is where I put the title, code, and emblem description.

The code looks like this:

badge_name_CÓDIGO DO EMBLEMA=NOME DO EMBLEMA (TITULO DO EMBLEMA)
badge_desc_CÓDIGO DO EMBLEMA=DESCRIÇÃO DO EMBLEMA

And I wanted to know if I could create this without being manually. Of course, to add a badge, I need to duplicate this content and change the code, title, and description.

I wanted to get it added like this:

    
asked by anonymous 18.02.2015 / 16:57

1 answer

1

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

    
18.02.2015 / 18:02