<?php function callback($buffer) { // replace all the apples with oranges return (str_replace("apples", "oranges", $buffer)); } ob_start("callback"); ?> <html> <body> <p>It's like comparing apples to oranges.</p> </body> </html> <?php ob_end_flush(); ?> 输出: <html> <body> <p>It's like comparing oranges to oranges.</p> </body> </html>
<?php ob_start(); echo "Hello "; $out1 = ob_get_contents(); echo "World"; $out2 = ob_get_contents(); ob_end_clean(); var_dump($out1, $out2); ?> 输出:string(6) "Hello " string(11) "Hello World" <?php //Level 0 ob_start(); echo "Hello "; //Level 1 ob_start(); echo "Hello World"; $out2 = ob_get_contents(); ob_end_clean(); //Back to level 0 echo "Galaxy"; $out1 = ob_get_contents(); ob_end_clean(); //Just output var_dump($out1, $out2); ?> 输出:string(12) "Hello Galaxy" string(11) "Hello World"
<?php ob_start(); echo "Hello "; $len1 = ob_get_length(); echo $len1; ?> 输出:6
<?php echo ob_get_level(); // --> 1 ?> <?php ob_end_clean(); echo ob_get_level(); // --> 0 ?> <?php echo ob_get_level(); // 1 ob_start(); echo "Hello "; echo ob_get_level(); // 2 ob_start(); echo "Hello World"; echo ob_get_level(); // 3 $out2 = ob_get_contents(); ob_end_clean(); echo "Galaxy"; $out1 = ob_get_contents(); ob_end_clean(); echo ob_get_level(); // 1 var_dump($out1, $out2); ?> 输出:11string(13) "Hello 2Galaxy" string(12) "Hello World3"
<?php ob_start(); echo "1"; $content = ob_get_clean(); ob_start(); // This is NECESSARY for the next ob_get_clean() to work as intended. echo "2"; $content .= ob_get_clean(); echo $content; ?> 输出: 12
(6)bool ob_end_clean ( void )
此函数丢弃最顶层输出缓冲区的内容并关闭这个缓冲区。如果想要进一步处理缓冲区的内容,必须在ob_end_clean()之前调用ob_get_contents(),因为当调用ob_end_clean()时缓冲区内容将被丢弃。
返回值:成功时返回 TRUE, 或者在失败时返回 FALSE。 错误的原因首先是,在调用时没有一个起作用的缓冲区,或者是因为某些原因缓冲区不能被删除(可能对特殊缓冲区而言)。
错误/异常: 如果函数失败了,将引发一个E_NOTICE异常。
<?php //using output_buffering=On print_r(ob_list_handlers()); //save buffer in a file $buffer = ob_get_flush(); file_put_contents('buffer.txt', $buffer); print_r(ob_list_handlers()); ?> 输出: Array ( [0] => default output handler ) Array ( )
3.总结
flush — 刷新输出缓冲
ob_clean — 清空(擦掉)输出缓冲区
ob_end_clean — 清空(擦除)缓冲区并关闭输出缓冲
ob_end_flush — 冲刷出(送出)输出缓冲区内容并关闭缓冲
ob_flush — 冲刷出(送出)输出缓冲区中的内容
ob_get_clean — 得到当前缓冲区的内容并删除当前输出缓冲
ob_get_contents — 返回输出缓冲区的内容
ob_get_flush — 刷出(送出)缓冲区内容,以字符串形式返回内容,并关闭输出缓冲区
ob_get_length — 返回输出缓冲区内容的长度
ob_get_level — 返回输出缓冲机制的嵌套级别
ob_start — 打开输出控制缓冲