Get a return from the echo

I work with some features that output echo. But I need them return, so I can use them in PHP.

It works (seemingly without a bitch), but I wonder if there is a better way?

    function getEcho( $function ) {
        $getEcho = '';
        ob_start();
        $function;
        $getEcho = ob_get_clean();
        return $getEcho;
    }

Example:

    //some echo function
    function myEcho() {
        echo '1';
    }

    //use getEcho to store echo as variable
    $myvar = getEcho(myEcho());      // '1'
+5
source share
4 answers

no, the only way I can think of is to β€œcatch” the echo instructions to use output buffering, as you already did. I use a very similar function in my code:

function return_echo($func) {
    ob_start();
    $func;
    return ob_get_clean();
}

it is only 2 lines shorter and does the same.

+10
source

Your first code is correct. Could be shortened, though.

  function getEcho($function) {
        ob_start();
        $function;
        return ob_get_clean();
    }
    echo getEcho($function);
+6
source

- .

+2

? :

  • .
  • An additional set of function calls, wordpress style, so that "somefunc ()" draws direct output, and "get_somefunc ()" returns the result instead
  • Add an extra parameter to the functions to signal whether they should be displayed or returned, like an icon print_r()'s.
+1
source

All Articles