Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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');
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.