Saving php output in a file
18,337
Solution 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);
Solution 2
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
Author by
user712027
Updated on June 04, 2022Comments
-
user712027 almost 2 years
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
-
CSᵠ almost 13 yearsdon't use fopen(), but instead file_put_contents()
-
user712027 almost 13 yearsSorry 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!
-
Marc B almost 13 years@Ash: nothing. f_p_c() is just a glorified wrapper around fopen/fwrite/fclose. All you do is save yourself 2 lines of code.
-
Colin Smillie almost 11 yearsShould be 'contents' instead of 'content'