PHP print_r大数组到变量不起作用 [英] PHP print_r large array to variable not working
问题描述
我正在尝试将大数组print_r压缩到文件中以对其进行调试.我尝试了2种方法:
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));
和
$arr = get_large_array();
ob_start();
print_r($arr);
file_put_contents('file.txt', ob_get_contents());
ob_end_clean();
在这两种情况下,都不会创建file.txt
,并且正在回显$arr
,就像运行了print_r($arr)
一样.这是怎么回事?
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?
推荐答案
问题在于,在内部,print_r($arr, true)
像在第二个示例中一样简单地使用输出缓冲.因此,在幕后,这两种方法都是等效的.但是为什么输出缓冲不起作用?
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?
我很感兴趣,我用$arr = array();
替换了$arr = get_large_array();
.令我惊讶的是,创建了file.txt
并且没有任何输出.我有个主意我将$arr
改回了大数组,运行了代码,然后向下滚动到输出的末尾.果然,它被截断了.我查看了错误日志,在print_r
行上发生了20个左右的内存不足"错误.在处理大型数组时,print_r
内存不足,崩溃并忽略了file_put_contents
和ob_end_clean
,显示了上述症状.
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');
这篇关于PHP print_r大数组到变量不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!