Home > Backend Development > PHP Tutorial > The php ob_start() function implements cache output of the current page content_PHP tutorial

The php ob_start() function implements cache output of the current page content_PHP tutorial

WBOY
Release: 2016-07-13 10:49:10
Original
1005 people have browsed it

Page caching is to save the page to a file and directly call the file the next time it is read without querying the database. Here we introduce the use of ob_start() to achieve it.


Example

Here we can focus on the usage skills of this method. Using this method can achieve the convenience of generating static pages!
The code is as follows
 代码如下 复制代码

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
//或直接用 file_put_content('info.txt',$info);
?>

Copy code

ob_start(); //Open buffer

phpinfo(); //Use phpinfo function

$info=ob_get_contents(); //Get the contents of the buffer and assign it to $info

$file=fopen(’info.txt’,’w’); //Open the file info.txt

fwrite($file,$info); //Write information to info.txt
代码如下 复制代码

ob_start();
$phpinfo = phpinfo();
//写入文件
ob_end_flush();

或者还有这样的用途:

ob_start(); //打开缓冲区
echo "Hellon"; //输出
header("location:index.php"); //把浏览器重定向到index.php
ob_end_flush();//输出全部内容到浏览器

fclose($file); //Close the file info.txt

//Or use file_put_content('info.txt',$info) directly;

?>

 代码如下 复制代码

< ? php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
? >
< html >
< body >

It's like comparing apples to oranges.


< / body >
< / html >
< ?php
ob_end_flush();
? >

以上程序会输出:

< html >
< body >
< p>It's like comparing oranges to oranges.
< / body >
< / html >

The above method can save the phpinfo information of different users.
And using this method is more reasonable and efficient than using file_get_conents().

Let’s talk about an application simply. For example, if you want to write the contents of phpinfo() to a file, you can do this:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template