ThinkPHP中实现gzip压缩

ThinkPHP中似乎没有对gzip的配置选项。不过实现起来还是挺简单的。以下是对 ThinkPHP 2.1 的修改方法。

首先要确定空间是否支持Zlib, 然后找ThinkPHP的控制输出函数output()。
控制输出的文件在 ThinkPHP/Lib/Think/Core 文件夹下,文件名 View.class.php。

     /**
     +----------------------------------------------------------
     * 输出模板
     +----------------------------------------------------------
     * @access protected
     +----------------------------------------------------------
     * @param string $content 模板内容
     * @param boolean $display 是否直接显示
     +----------------------------------------------------------
     * @return mixed
     +----------------------------------------------------------
     */
    protected function output($content,$display) {
        if(C('HTML_CACHE_ON'))  HtmlCache::writeHTMLCache($content);
        if($display) {
            if(false !== strpos($content,'{__RUNTIME__}'))
            {
                $runtime = C('SHOW_RUN_TIME')? '
<div id="think_run_time" class="think_run_time">'.$this->showTime().'</div>

' : '';
                $content = str_replace('{__RUNTIME__}', $runtime, $content);
            }
			if(extension_loaded('zlib')){//检查服务器是否开启了zlib拓展
				ob_start('ob_gzhandler');
			}
			ob_start("compress");
			function compress($buffer) {//去除文件中的注释
				$buffer = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $buffer);
				return $buffer;
			  }
            echo $content;
            if(C('SHOW_PAGE_TRACE'))   $this->showTrace();

			if(extension_loaded('zlib')){
			  ob_end_flush();//输出buffer中的内容,即压缩后的css文件
			}
            return null;
        }else {
            return $content;
        }
    }
affiliate_link
Share this Post:
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

No Responses to “ThinkPHP中实现gzip压缩”

Leave a Reply:

Name (required):
Mail (will not be published) (required):
Website:
Comment (required):
XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>