先來看ob_start用法,使用PHP ob_start()函數打開browser的cache,這樣可以保證cache的內容在你調用flush(),ob_end_flush()(或程序執行完畢)之前不會被輸出,代碼如下:
- <?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
- ?>
PHP ob_start()函數一個很大的特點;也可以使用ob_start的參數,在cache被寫入后,然后自動運行命令,比如ob_start(”ob_gzhandler”);而我們最常用的做法是用ob_get_contents()得到cache中的內容面的代碼是一個壓縮網頁的例子,我 們利用ob_gzip函數,使用ob_start將輸出內容壓縮后放到“緩沖區”后再輸出,代碼如下:
- //啟用壓縮
- if(function_exists('ob_gzip'))
- {
- ob_start('ob_gzip');
- }
- //準備一些待壓縮的內容
- for($i=0; $i<100; $i++)
- {
- echo('這里是測試內容 <br>');
- }
- //輸出壓縮成果
- ob_end_flush();
- //這是ob_gzip壓縮函數
- function ob_gzip ($content)
- {
- if( !headers_sent() && extension_loaded ("zlib") && strstr ( $_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")){
- $content = gzencode($content,9);
- header ("Content- Encoding: gzip");
- header ("Vary: Accept- Encoding");
- header ("Content- Length: ".strlen ($content));
- }
- return ($content) ;
- }
新聞熱點
疑難解答