Open In App

PHP ob_get_contents() Function

Last Updated : 18 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The ob_get_contents() is an inbuilt function in PHP that is used to capture what is currently being buffered by the output buffer. This function returns the output buffer.

Syntax

ob_get_contents(): string | false

Parameter 

This function does not accept any parameters.

Return Value 

The ob_get_contents() function in PHP returns the contents of the output buffer as a string. If this function does not return any content buffer then it will return false.

Program 1: The following program demonstrates the ob_get_contents() Function.

PHP




<?php
ob_start();
  
echo "This is some text in the output buffer.";
$bufferContents = ob_get_contents();
  
ob_end_clean();
  
// Output the stored contents
echo "Contents of the output buffer: " . $bufferContents;
?>


Output:

Contents of the output buffer: This is some text in the output buffer. 

Program 2: The following program demonstrates the ob_get_contents() Function.

PHP




<?php
ob_start();
echo "Today's date is: " . date("Y-m-d");
  
$bufferContents = ob_get_contents();
ob_end_clean();
  
$modifiedContents = str_replace("date", "time", $bufferContents);
echo $modifiedContents;
?>


Output:

Today's time is: 2023-07-25 

Program 3: The following program demonstrates the ob_get_contents() function.

PHP




<?php
ob_start();
  
// Generate some output in a loop
for ($i = 1; $i <= 5; $i++) {
    echo "Line $i: GEEKS for GEEKS .<br>";
}
$bufferContents = ob_get_contents();
ob_end_clean();
  
// Modify the captured contents
$modifiedContents = strtoupper($bufferContents);
  
// Output the modified contents
echo $modifiedContents;
?>


Output:

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads