ryanve
ryanve

Reputation: 52601

get return from echo

I'm working with some functions that echo output. But I need their return so I can use them in PHP.

This works (seemingly without a hitch) but I wonder, is there 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'

Upvotes: 5

Views: 3706

Answers (5)

Rahul
Rahul

Reputation: 1

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

Upvotes: 0

oezi
oezi

Reputation: 51817

no, the only way i can think of to "catch" echo-statements it to use output-buffering like you already do. i'm using a very similar function in my code:

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

it's just 2 lines shorter and does exactly the same.

Upvotes: 10

Marc B
Marc B

Reputation: 360872

Did you write these functions? You can go 3 ways:

  1. Using your wrapper to do capturing via output buffering.
  2. Extra set of functions calls, wordpress style, so that "somefunc()" does direct output, and "get_somefunc()" returns the output instead
  3. Add an extra parameter to the functions to signal if they should output or return, much like print_r()'s flag.

Upvotes: 1

Mob
Mob

Reputation: 11106

Your first code is correct. Can be shortened though.

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

Upvotes: 6

Yeroon
Yeroon

Reputation: 3243

Your first piece of code is the only way.

Upvotes: 2

Related Questions