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

user712027
  • 572
  • 6
  • 9
  • 22

2 Answers2

17

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
florian h
  • 1,162
  • 1
  • 10
  • 24
David Conde
  • 4,631
  • 2
  • 35
  • 48
2

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); 
Naftali
  • 144,921
  • 39
  • 244
  • 303