頁面緩存就是把頁面保存到一個文件中,下次讀出時直接調用文件而不查詢數據庫,這里我們介紹利用ob_start()來實現.
例,代碼如下:
- <?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
- //或直接用 file_put_content('info.txt',$info);
- ?>
以上的方法,可以把不同用戶的phpinfo信息保存下來,這里我們可以著重看看這個方法的使用技巧,用這個方法可以實現生成靜態頁面的便利.
并且用這個方法比用file_get_conents()的方法更合理更有效率,簡單的說個應用吧,比如想要把phpinfo()的內容寫入文件,可以這樣做:
- ob_start();
- $phpinfo = phpinfo();
- //寫入文件
- ob_end_flush();
- 或者還有這樣的用途:
- ob_start(); //打開緩沖區
- echo "Hellon"; //輸出
- header("location:index.php"); //把瀏覽器重定向到index.php
- ob_end_flush();//輸出全部內容到瀏覽器
header()會發送一段文件頭給瀏覽器,但是如果在header()之前已經有了任何輸出(包括空輸出,比如空格,回車和換行)就會報錯,但是如果輸出在ob_start()和ob_end_flush()之間,就會沒有問題,因為在輸出前打開了緩沖區,echo后面的字符就不會輸出到瀏覽器,而是保留在服務器,知道使用flush才會輸出,所以header()會正常執行.
當然,ob_start()還可以有參數,參數就是一個回調函數,例子如下:
- <? 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>
新聞熱點
疑難解答