How to capture php code or included file output in a variable

Sometimes we want to reuse a php function or include a file and want to capture  the output (from echo, print, etc.) of that function/file to a variable. I had to do this in wordpress but the code is same for any php software.

Capture php output of file include

We can use php functions ob_start() and ob_get_clean() to start output buffering and get the content of the buffer. Here is sample php code snippet:

include(ABSPATH . 'path/to/include/file.php');
$content = ob_get_clean();

ob_get_clean() gets the buffer content, cleans the buffer and ends the buffering. There are couple of other ob_ functions for more flexibility. But I was able to manage with just these two.

Capture php output of function call

Here is sample php code snippet for function call

function_foo("var1", "var2");
$content = ob_get_clean();

Nested ob_start calls

ob_start and ob_get_clean() calls can be nested also. Here is how cascaded calls will look like:

function f1() {
  echo "f1";
function f2() {
  echo "f2";

$content_inner = ob_get_clean();
$content_outer = ob_get_clean();
print "content_inner=$content_inner\n";
print "content_outer=$content_outer\n";

Here is the the outcome of above code when executed using php on command line:



Here are some benefits of output buffering:

  1. It becomes much easier to re-use an existing code which you don’t want to modify.
  2. Often keeping html code in separate file with php embedded in it is more convenient than it being is pure php form. Using output buffering that code output can easily be capture in a variable.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments