emlog无插件实现网站源码压缩
[ 2015/05/08, Emlog , 3202阅, 0评 ]

在以往的Emlog优化教程中,相信都是使用的代码压缩插件,今天主要是分享插件的代码版本,也就是不使用插件,直接将代码丢在module.php中就可以,好吧,又消灭一个插件!

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

  1. function em_compress_html_main($buffer){
  2. $initial=strlen($buffer);
  3. $buffer=explode("<!--em-compress-html-->", $buffer);
  4. $count=count ($buffer);
  5. for ($i = 0; $i <= $count; $i++){
  6. if (stristr($buffer[$i], '<!--em-compress-html no compression-->')){
  7. $buffer[$i]=(str_replace("<!--em-compress-html no compression-->", " ", $buffer[$i]));
  8. }else{
  9. $buffer[$i]=(str_replace("\t", " ", $buffer[$i]));
  10. $buffer[$i]=(str_replace("\n\n", "\n", $buffer[$i]));
  11. $buffer[$i]=(str_replace("\n", "", $buffer[$i]));
  12. $buffer[$i]=(str_replace("\r", "", $buffer[$i]));
  13. while (stristr($buffer[$i], ' '))
  14. {
  15. $buffer[$i]=(str_replace(" ", " ", $buffer[$i]));
  16. }
  17. }
  18. $buffer_out.=$buffer[$i];
  19. }
  20. $final=strlen($buffer_out);
  21. $savings=($initial-$final)/$initial*100;
  22. $savings=round($savings, 2);
  23. $buffer_out.="\n<!--压缩前的大小: $initial bytes; 压缩后的大小: $final bytes; 节约:$savings% -->";
  24. return $buffer_out;
  25. }

以下代码是扔在footer.php最末尾(即结尾处)

  1. <?php
  2. if(_g('compress_html')=='open'){
  3. $html=ob_get_contents();
  4. ob_get_clean();
  5. echo em_compress_html_main($html);
  6. }
  7. ?>

以上的代码有一个模板设置判断语句,其代码为以下:

  1. 'compress_html' => array(
  2. 'type' => 'radio',
  3. 'name' => '网站源码压缩',
  4. 'description' => '',
  5. 'values' => array('open' => '压缩','close' => '关闭'),
  6. 'default' => 'open'
  7. ),

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

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

原文:http://www.33665.net/emlog/204.html

有朋自远方来...评论一下呗O(∩_∩)O