相信大家用过CDN加速的都知道,CDN都有GZIP压缩功能,把网站图片以及代码压缩后在传送到客户端实现更快的网页加载速度,在以往的Emlog优化教程中,相信都是使用的代码压缩插件,今天主要是分享插件的代码版本,也就是不使用插件,直接将代码丢在module.php中就可以,好吧,又消灭一个插件!以下是具体的操作方法以及注意事项。

温馨提示

编写代码基本功,操作以下步骤前请备份好模板文件以免不适配不可逆。或创建模板压缩包下载,如网站乱码后可恢复。

第一步

以下代码是扔在module.php里面的

function em_compress_html_main($buffer){
    $initial=strlen($buffer);
    $buffer=explode("<!--em-compress-html-->", $buffer);
    $count=count ($buffer);
    for ($i = 0; $i <= $count; $i++){
        if (stristr($buffer[$i], '<!--em-compress-html no compression-->')){
            $buffer[$i]=(str_replace("<!--em-compress-html no compression-->", " ", $buffer[$i]));
        }else{
            $buffer[$i]=(str_replace("\t", " ", $buffer[$i]));
            $buffer[$i]=(str_replace("\n\n", "\n", $buffer[$i]));
            $buffer[$i]=(str_replace("\n", "", $buffer[$i]));

            $buffer[$i]=(str_replace("\r", "", $buffer[$i]));
            while (stristr($buffer[$i], '  '))
            {
            $buffer[$i]=(str_replace("  ", " ", $buffer[$i]));
            }
        }
        $buffer_out.=$buffer[$i];
    }
    $final=strlen($buffer_out);
    $savings=($initial-$final)/$initial*100;
    $savings=round($savings, 2);
    $buffer_out.="\n<!--压缩前的大小: $initial bytes; 压缩后的大小: $final bytes; 节约:$savings% -->";
    return $buffer_out;
}

第二步

以下代码是扔在footer.php文件的最后面,放在html或body标签结尾处。

    <?php
    if(_g('compress_html')=='open'){
            $html=ob_get_contents();
            ob_get_clean();
            echo em_compress_html_main($html);
    }
    ?>

第三步

以上的代码有一个模板设置判断语句,也就是源码压缩的开关,放在你当前使用模板下的options.php文件内,放在合适的位置即可

    'compress_html' => array(
            'type' => 'radio',
            'name' => '网站源码压缩',
            'description' => '',
            'values' => array('open' => '压缩','close' => '关闭'),
            'default' => 'open'
        ),

第四步

如果想要内容里面的pre不被压缩可使用以下函数:

function unCompress($content){
    if(preg_match_all('/(crayon-|<\/pre>)/i', $content, $matches)) {
        $content = '<!--em-compress-html--><!--em-compress-html no compression-->'.$content;
        $content.= '<!--em-compress-html no compression--><!--em-compress-html-->';
    }
    return $content;
}
unCompress($log_content);

第五步

就此就部署代码完毕了,与emlog官网发布的压缩插件其实是一个道理。只是插件来的方便一些。当然啦!免费的肯定是要废点时间的。最后呢就是在后台的模板设置里开启这个功能就行了!