Home >Backend Development >PHP Tutorial >Detailed explanation of the usage of php ob_start() cache function
This article introduces the usage of the function ob_start() used for cache control in PHP. Friends in need can refer to it.
In php, the ob_start() function is used to open the buffer. For example, if there is output before the header() function, including carriage return/space/line feed/, there will be an error of "Header had all ready send by". At this time, you can first use ob_start() to open the buffer. The data block of the php code and the echo() output will enter the buffer and will not be output immediately. There are four ways to open a buffer in php: 1. Used before header() <?php ob_start(); //打开缓冲区 echo /"Hellon/"; //输出 header("location:index.php"); //把浏览器重定向到index.php ob_end_flush();//输出全部内容到浏览器 ?> 2. The phpinfo() function can obtain client and server information and use a buffer to save client information. <?php ob_start(); //打开缓冲区 phpinfo(); //使用phpinfo函数 $info=ob_get_contents(); //得到缓冲区的内容并且赋值给$info $file=fopen(/'info.txt/',/'w/'); //打开文件info.txt fwrite($file,$info); //写入信息到info.txt fclose($file); //关闭文件info.txt ?> 3. Static page technology <?php ob_start();//打开缓冲区 //php页面的全部输出 $content = ob_get_contents();//取得php页面输出的全部内容 $fp = fopen("output00001.html", "w"); //创建一个文件,并打开,准备写入 fwrite($fp, $content); //把php页面的内容全部写入output00001.html,然后…… fclose($fp); ?> 4, output code <?php Function run_code($code) { If($code) { ob_start(); eval($code); $contents = ob_get_contents(); ob_end_clean(); }else { echo "错误!没有输出"; exit(); } return $contents; } |