PHP command line output buffer outputs regardless of buffer settings

半世苍凉 提交于 2019-12-04 11:20:54

问题


I have some classes I am writing unit tests for which have echoes in them. I want to suppress this output and thought ob_start() and ob_clean() would suffice, but they aren't having an effect.

public function testSomething (){
    ob_start();
    $class = new MyClass();
    $class->method();
    ob_clean();
}

I've also tried variations such as ob_start(false, 0, true); and ob_end_clean() to no avail.

What am I missing?


回答1:


you may want something like this

<?php
public function testSomething (){
    ob_start();
    ob_implicit_flush(false); // turn off implicit flush

// Make your output below
    $class = new MyClass();
    $class->method();
// End of output

// store output into variable:
    $output = ob_get_contents();
}
?>



回答2:


Do you have implicit_flush set to true in your PHP ini? This can cause the behaviour you are seeing as it tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print() or echo() and each and every HTML block.




回答3:


The following solves this problem for me. Without calling ob_end_clean(), the contents of the buffer remain until the script's end, where it is flushed.

ob_implicit_flush(false);
ob_start();    
/*
  ...
  ... do something that pushes countent to the output buffer
  ...
*/    
$rendered = ob_get_contents();
ob_end_clean(); // Needed to clear the buffer


来源:https://stackoverflow.com/questions/5461175/php-command-line-output-buffer-outputs-regardless-of-buffer-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!