1、ob缓存php
ob的基本原则:若是ob缓存打开,则echo的数据首先放在ob缓存。若是是header信息,直接放在程序缓存。当页面执行到最后,会把ob缓存的数据放到程序缓存,而后依次返回给浏览器。html
ob的基本做用:浏览器
1) 防止在浏览器有输出以后再使用setcookie()、header()或session_start()等发送头文件的函数形成的错误。其实这样的用法少用为好,养成良好的代码习惯。
2) 捕捉对一些不可获取的函数的输出,好比phpinfo()会输出一大堆的HTML,可是咱们没法用一个变量例如$info=phpinfo();来捕捉,这时候ob就管用了。
3) 对输出的内容进行处理,例如进行gzip压缩,例如进行简繁转换,例如进行一些字符串替换。
4) 生成静态文件,其实就是捕捉整页的输出,而后存成文件。常常在生成HTML,或者整页缓存中使用。缓存
一、开启cookie
//此函数将打开输出缓冲。当输出缓冲激活后,脚本将不会输出内容(除http标头外),相反须要输出的内容被存储在内部缓冲区中。 ob_start ([ callback $output_callback [, int $chunk_size [, bool $erase ]]] ) : bool
<?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(); ?>
二、获取内容session
//只是获得输出缓冲区的内容,但不清除它。 ob_get_contents ( void ) : string
//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);
//获得当前缓冲区的内容并删除当前输出缓冲区。 ob_get_clean ( void ) : string
//刷出(送出)缓冲区内容,以字符串形式返回内容,并关闭输出缓冲区。 ob_get_flush ( void ) : string
三、清空数据app
//此函数用来丢弃输出缓冲区中的内容。 ob_clean ( void ) : void
//清空(擦除)缓冲区并关闭输出缓冲 ob_end_clean ( void ) : bool
四、刷新函数
//冲刷出(送出)输出缓冲区中的内容 ob_flush ( void ) : void
// 冲刷出(送出)输出缓冲区内容并关闭缓冲 ob_end_flush ( void ) : bool
//刷出(送出)缓冲区内容,以字符串形式返回内容,并关闭输出缓冲区。 ob_get_flush ( void ) : string
五、关闭spa
// 冲刷出(送出)输出缓冲区内容并关闭缓冲 ob_end_flush ( void ) : bool
//清空(擦除)缓冲区并关闭输出缓冲 ob_end_clean ( void ) : bool
简单案例:code
<?php /** * Created by PhpStorm. * User: 25754 * Date: 2019/8/31 * Time: 9:46 */ $file = "./index/index.html"; if (file_exists($file) && filemtime($file) + 10 > time()) { echo "输出缓存内容"; include "./index/index.html"; } else { //开启ob缓存 ob_start(); include "./tmp.html"; //获取缓冲区内容 $content = ob_get_contents(); file_put_contents("./index/index.html", $content); //发送内部缓冲区的内容到浏览器,而且关闭输出缓冲区 ob_end_flush(); }