Skip to content
Advertisement

How can i save all the variable results from a echo into a txt file using php?

I wrote a php script that generates random tokens, and I want to output these tokens into a .txt file.

Below is the code:

JavaScript

It echos multiple tokens, until the echo = e3b0, but when I try to write the result on a txt file, it only writes “e3b0”, is that a way to write all the results of the “echo” into a txt file?

Advertisement

Answer

EDIT: Efficiency was never asked in original OP question. This post is being edited to include efficiency, namely no need to reopen and close a file.

Your use of w+ will always place the file pointer at the beginning of the file and truncate the file in the process. So as a result, you always end up with the last value written.

From php.net on fopen w+:

JavaScript

Using your existing code, a solution then would be as follows:

$myfile = fopen(“output.txt”, “a+”) or die(“Unable to open file!”);

JavaScript

fclose($myfile);

Where a+ in the same docs says:

JavaScript

Source: https://www.php.net/manual/en/function.fopen.php

Amendments:

As @andreas mentions, opening and closing the file repeatedly inside the loop is not necessary (nor efficient). Since you are appending, you can open it once with a+ before the loop begins; and close it after the loop ends.

In terms of having a separator char between tokens written to the file, a carriage return (line break) is a good choice. In this way you can reduce the amount of parsing you would have to program when programmatically reading the file. For this, your writes could be written as follows:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement