Sunday, September 22, 2024
Google search engine
HomeLanguagesPHP ob_get_contents() Function

PHP ob_get_contents() Function

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments