1

I'm trying to print_r a large array to a file to debug it. I've tried 2 methods:

$arr = get_large_array();
file_put_contents('file.txt', print_r($arr, true));

and

$arr = get_large_array();
ob_start();
print_r($arr);
file_put_contents('file.txt', ob_get_contents());
ob_end_clean();

In both cases, file.txt is not being created, and $arr is being echoed just like as if I had run print_r($arr). What's going on here?

Joel
  • 2,654
  • 6
  • 31
  • 46

1 Answers1

3

The problem is that internally, print_r($arr, true) simply uses output buffering as in the second example. So behind the scenes, both methods are equivalent. But why is output buffering not working?

Intrigued, I replaced $arr = get_large_array(); with $arr = array();. To my surprise, file.txt was created and there was no output. I had an idea. I changed $arr back to the large array, ran the code, and scrolled down to the end of the output. Sure enough, it was being truncated. I looked in the error log, and there were 20 or so "out of memory" errors occurring on the print_r line. In dealing with the large array, print_r ran out of memory, crashed and ignored the file_put_contents and the ob_end_clean, displaying the aforementioned symptoms.

For me, the solution was to increase the memory limit:

ini_set('memory_limit', '1024M');
Joel
  • 2,654
  • 6
  • 31
  • 46