Becky
Becky

Reputation: 5585

Add data to text with print_r()

I have a text file and each time a visitor access this page I am doing a print_r() to it.

How can I use print_r() to add data to my file.txt text file ? Currently the text is overwritten and stores only last print_r().

$output = print_r($data, true);
file_put_contents('file.txt', $output);

Upvotes: 0

Views: 449

Answers (3)

Martin
Martin

Reputation: 22760

Method 1:

Appending data to the bottom (end) of the file.

file_put_contents($fileDestination,print_r($data,true),FILE_APPEND)

Method 2:

Append data to the top (start) of the file.

$fileDestination = "/path/to/your/file.txt";
$oldData = "";
/***
 Edit some catching if file exists
 ***/
 if(file_exists($fileDestination)){
   $oldData = file_get_contents($fileDestination,false, null, 0);
 }
$saveData = print_r($data,true).PHP_EOL.$oldData;
unset($oldData);
file_put_contents($fileDestination,$saveData);

Method 2 Explanation:

get the data from within the file, this data is held in a variable in the order it appears in the file. You then get your print_r data and then append a line break to it and add the old file data so that the new data appears at the top of the file, then writing the whole chunk back into the file, overwriting what currently exists there.

PHP_EOL is the PHP End of Line character and is used for line breaks.

Upvotes: 0

Daniel Dudas
Daniel Dudas

Reputation: 3002

You need to set the flag FILE_APPEND to append the $output at the end of the file.

file_put_contents('file.txt', $output, FILE_APPEND);

Upvotes: 1

j08691
j08691

Reputation: 207953

You can use the FILE_APPEND flag:

file_put_contents('file.txt', $output, FILE_APPEND);

FILE_APPEND If file filename already exists, append the data to the file instead of overwriting it.

Upvotes: 4

Related Questions