PHP ob_get_contents() Function

What is PHP ob_get_contents() Function?

If you want to know what is stored in the output buffer till this moment, use ob_get_contents() function. Remember, it returns content that is stored after starting the last ob_start() function. You can save it in a variable.

Syntax:

ob_get_contents()

Parameters:

This function has no parameter.

Return Values:

The function returns –

  • Content of the last buffer, if buffer is active (Check example 1).
  • Empty string, if buffer is inactive (Check example 2).

Examples:

Example 1:

<?php
   ob_start();
   echo str_pad("This content is from 2nd buffer.", 4096);

   ob_start();
   echo str_pad("This content is from 3nd buffer.", 4096). "<br />";
   echo "Content of the ob_get_contents is: ". ob_get_contents();
?>

Output:

This content is from 2nd buffer. This content is from 3nd buffer.
Content of the ob_get_contents is: This content is from 3nd buffer.

Explanation:

The ob_get_contents() function returns the content of that buffer where it exist. It exists in 3rd buffer level.

Example 2:

<?php
   echo str_pad("This is first line.",4096)."<br />";
   $ob_val = ob_get_contents();
   echo "Content of the ob_get_contentsis:".$ob_val.".";
?>

Output:

This is first line.
Content of the ob_get_contentsis:.

Explanation:

As ob_start() has not been declared to initiate a buffer, the ob_get_contents() function doesn’t find anything to display. So, it displays an empty string.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP ob_get_contents() Function

PHP ob_get_contents() function is a built-in PHP function and part of the PHP’s Output Control functions. It only brings the content of the active output buffer without doing anything like deleting it or turning off the buffer level etc.

Reference:

https://www.php.net/manual/en/function.ob-get-contents.php