How do I capture PHP output into a variable?

In PHP, you can use the output control functions to capture the output of a PHP script into a variable. The two functions you can use for this are ob_start() and ob_get_contents().

  1. First, call ob_start() at the beginning of your script to turn on output buffering. This tells PHP to store any output generated by your script in a buffer instead of sending it to the browser.

  2. Next, run the code that generates the output you want to capture.

  3. Finally, call ob_get_contents() to retrieve the contents of the buffer and store it in a variable. This function returns the contents of the buffer as a string.

Watch a course Learn object oriented PHP


echo "Hello, World!";
$output = ob_get_contents();
echo $output;

This will capture the echo statement "Hello, World!" and store it in the $output variable.

You may also use ob_get_clean() function which will clean the buffer and return the output.

echo "Hello World!";
$output = ob_get_clean();
echo $output; // outputs "Hello World!"

It will return the output and clean the buffer both.