2

I have:

echo"<br>";echo"<br><pre>";print_r($array2);echo"</pre>";
echo"<br>";echo"<br><pre>";print_r($array3);echo"</pre>";
 echo"<br>";echo"<br><pre>";print_r($array4);echo"</pre>";

I need to save what all of these print_r print into a file (without pronting anything in the page).

I know I need to do something like that:

$f = fopen("file.txt", "w");
fwrite($f, "TEXT TO WRITE");
fclose($f); 

But I don't know how to put the contents before in it.

Thansk a million

0

3 Answers 3

18

You can use Output Buffering, which comes pretty handy when you want to control what you output in your PHP scripts and how to output it. Here's a small sample:

ob_start();
echo"<br>";echo"<br><pre>";print_r($array2);echo"</pre>";
echo"<br>";echo"<br><pre>";print_r($array3);echo"</pre>";
echo"<br>";echo"<br><pre>";print_r($array4);echo"</pre>";

$content = ob_get_contents();

$f = fopen("file.txt", "w");
fwrite($f, $content);
fclose($f); 

EDIT: If you dont want to show the output in your page, you just have to call ob_end_clean():

ob_start();
//...

$content = ob_get_contents();
ob_end_clean();
//... write the file, either with fopen or with file_put_contents
Sign up to request clarification or add additional context in comments.

4 Comments

don't use fopen(), but instead file_put_contents()
Sorry David, I forgot to mention: cannot show the prints in my page, I mean, instead of showing the print_r I have to save the output of the prints in the file. Thanks!
@Ash: nothing. f_p_c() is just a glorified wrapper around fopen/fwrite/fclose. All you do is save yourself 2 lines of code.
Should be 'contents' instead of 'content'
1

Try this out using the true param in the print_r:

$f = fopen("file.txt", "w");
fwrite($f, print_r($array2, true));
fwrite($f, print_r($array3, true));
fwrite($f, print_r($array4, true));
fclose($f); 

Comments

0

Another way to save all output to a file using ob_start() (before any output) with callback function:

ob_start(function ($buffer) {
    file_put_contents('file.txt', $buffer, FILE_APPEND);
    return $buffer; // remove this line if you dont want to show the output
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.