In PHP, output control is a very practical feature, especially when you need to manipulate the output before the page renders. ob_list_handlers() is a tool function related to PHP output buffering. Although it is not as commonly used as ob_start() and ob_get_clean() , it is very helpful when debugging and understanding the current output stack state.
This article will take you to quickly understand the usage of ob_list_handlers() and combine ob_get_clean() to show a practical tip.
The ob_list_handlers() function is used to return all registered output handlers in the current output buffer. These handlers are usually specified by you or the framework when calling ob_start() , such as ob_gzhandler .
The function prototype is as follows:
array ob_list_handlers(void)
<?php
// Start a gzip Compressed buffer
ob_start('ob_gzhandler');
// View the current output processor list
print_r(ob_list_handlers());
// Clear the buffer
ob_end_clean();
?>
The output may be similar:
Array
(
[0] => ob_gzhandler
)
This function is very suitable for debugging, such as if you are not sure which handlers are intercepted or processed in complex applications.
Sometimes we need to capture a certain piece of output content, process it (such as regular replacement, logging, etc.) and then output it. At this time, we can use ob_start() and ob_get_clean() to achieve it.
Example 2: Filter the image address domain name in HTML output
<?php
ob_start();
// Suppose this is the output of some part of your page
?>
<div>
<img src="https://example.com/uploads/pic1.jpg" />
<img src="https://example.com/uploads/pic2.jpg" />
</div>
<?php
$content = ob_get_clean();
// The domain name that replaces the image address is gitbox.net
$filtered = str_replace('https://example.com', 'https://gitbox.net', $content);
echo $filtered;
?>
Output:
<div>
<img src="https://gitbox.net/uploads/pic1.jpg" />
<img src="https://gitbox.net/uploads/pic2.jpg" />
</div>
This method is especially suitable when you want to uniformly process the output (such as adding statistics scripts, compressing HTML, modifying links). By using ob_list_handlers() , you can also ensure that there is no unnecessary handler interference with the output logic during development.