Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ob_get_contents work in Php?

This is a sample code from the book I am reading:

ob_start();
include("{$path}.ini");
$string = ob_get_contents();
ob_end_clean();
$pairs = parse_ini_string($string);

My question is, how does ob_get_contents() know what to get contents from? ({$path}.ini in this situation)?

like image 900
Koray Tugay Avatar asked Feb 03 '13 11:02

Koray Tugay


People also ask

What does Ob_get_contents do in PHP?

The ob_get_contents() function returns the contents of the topmost output buffer.

What is Ob_start () and Ob_end_flush () in PHP?

ob_end_flush() - Flush (send) the output buffer and turn off output buffering. ob_implicit_flush() - Turn implicit flush on/off. ob_gzhandler() - ob_start callback function to gzip output buffer. ob_iconv_handler() - Convert character encoding as output buffer handler.

What is use of Ob_end_clean in PHP?

The ob_end_clean() function deletes the topmost output buffer and all of its contents without sending anything to the browser.

What will be the output if we declare Ob_start () function in PHP?

The ob_start() function creates an output buffer. A callback function can be passed in to do processing on the contents of the buffer before it gets flushed from the buffer.


Video Answer


1 Answers

ob_get_contents simply gets the contents of the output buffer since you called ob_start(). Essentially, an output buffer in PHP catches anything that would have been output to the browser (excluding headers). It's useful in cases where you may need to filter some output, or you're using a PHP method (such as var_dump) that writes output directly to screen, and you would instead like the return value of the method in a string.

In this case, because you're include()ing the .ini file, it's contents will be essentially output to screen, and ob_get_contents() will get the content of the file.

If you were to put echo "I'm a little teapot short and stout"; underneath the include, this would also be included in $string after the body of the .ini file.

In your specific case, however, output buffering is an unnecessary overhead, simply use file_get_contents on the .ini file. I'm not sure why a book would even have this code in it at all.

like image 110
Rudi Visser Avatar answered Oct 19 '22 00:10

Rudi Visser