php ob_start(ob_gzhandler)進(jìn)行網(wǎng)頁(yè)壓縮
來(lái)源:程序員人生 發(fā)布時(shí)間:2014-05-31 15:32:53 閱讀次數(shù):3986次
先來(lái)看ob_start用法,使用PHP ob_start()函數(shù)打開(kāi)browser的cache,這樣可以保證cache的內(nèi)容在你調(diào)用flush(),ob_end_flush()(或程序執(zhí)行完畢)之前不會(huì)被輸出,代碼如下:
- <?php
- ob_start();
- phpinfo();
- $info=ob_get_contents();
- $file=fopen(’info.txt’,'w’);
- fwrite($file,$info);
- fclose($file);
- ?>
PHP ob_start()函數(shù)一個(gè)很大的特點(diǎn);也可以使用ob_start的參數(shù),在cache被寫(xiě)入后,然后自動(dòng)運(yùn)行命令,比如ob_start(”ob_gzhandler”);而我們最常用的做法是用ob_get_contents()得到cache中的內(nèi)容面的代碼是一個(gè)壓縮網(wǎng)頁(yè)的例子,我 們利用ob_gzip函數(shù),使用ob_start將輸出內(nèi)容壓縮后放到“緩沖區(qū)”后再輸出,代碼如下:
-
- if(function_exists('ob_gzip'))
- {
- ob_start('ob_gzip');
- }
-
- for($i=0; $i<100; $i++)
- {
- echo('這里是測(cè)試內(nèi)容 <br>');
- }
-
- ob_end_flush();
-
- 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) ;
- }
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)