CSV出力などで、大量のデータをブラウザに送る際、出力バッファを解除しておいたほうがいい。出力バッファが有効になったままだと、echoしたものは一旦メモリに蓄えられるため、結果的にメモリオーバになる危険性がある。
error_reporting(-1); ini_set('display_errors', 1); ob_start(); // 出力バッファ開始 while ( true ) { phpinfo(); }
Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 33300481 bytes) in /Applications/MAMP/htdocs/php/ob_filter/memory.php on line 10
出力バッファを解除するには、echoなどの直前で次のような関数を1回だけ実行するだけである。
function clearOutputBuffer() { while ( ob_get_level() > 0 ) { ob_end_clean(); } }