Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Suppress output within a function?

What is the simplest way to suppress any output a function might produce? Say I have this:

function testFunc() {
    echo 'Testing';
    return true;
}

And I want to call testFunc() and get its return value without "Testing" showing up in the page. Assuming this would be in the context of other code that does output other things, is there a good method for doing this? Maybe messing with the output buffer?

like image 634
Wilco Avatar asked Jan 28 '09 01:01

Wilco


3 Answers

Yes, messing with the Output Buffer is exactly the answer. Just turn it on before you call your method that would output (not the function itself, but where you call it, you could wrap it around your whole script or the script flow, but you can make it as "tight" as possible by just wrapping it around the call of the method):

function foo() {
  echo "Flush!";
  return true;
}

ob_start();
$a = foo();
ob_end_clean();

And no output is generated.

like image 155
Cody Caughlan Avatar answered Sep 27 '22 17:09

Cody Caughlan


Here you go:

ob_start();
testFunc();
ob_end_clean();

"ob" stands for "output buffering", take a look at the manual pages here: http://www.php.net/outcontrol

like image 45
Ray Hidayat Avatar answered Sep 27 '22 19:09

Ray Hidayat


Yes you are on the right track as to leveraging PHP's output buffering functions, i.e. ob_start and ob_end_clean (look them up on php.net):

<?php
  function testFunc() {
    echo 'Testing';
    return true;
  }

    ob_start();
    $output = testFunc();
    ob_end_clean();

    echo $output;
?>
like image 25
Dexygen Avatar answered Sep 27 '22 19:09

Dexygen