使用PHP来压缩CSS文件

这里将介绍使用PHP以一种简便的方式来压缩你的CSS文件。这种方法不需要命名你的.css文件和.php文件。
当前有许多方法需要将.css文件重命名成.php文件,然后在所有PHP文件中放置压缩代码。现在介绍这种技巧,不需要重命名CSS并且只需要一个PHP文件就能搞定。

那让我们看看是怎么实现,首先创建一个PHP文件,然后将下面的代码放到刚创建的PHP文件中。

<?php
// This defines the header type
header("Content-type: text/css");
 
// Start the output buffer
ob_start("compress_css");
 
// Function which actually compress
// The CSS file
function compress_css($buffer)
{
 /* remove comments */
 $buffer = preg_replace("!/\*[^*]*\*+([^/][^*]*\*+)*/!", "", $buffer) ;
 /* remove tabs, spaces, newlines, etc. */
 $arr = array("\r\n", "\r", "\n", "\t", "  ", "    ", "    ") ;
 $buffer = str_replace($arr, "", $buffer) ;
 return $buffer;
}

/* include all CSS files */
include("style.css");
include("fonts.css");
include("print.css");

// Flush the output buffer
ob_end_flush();
?>

这个方法使用了output buffer函数来实现,如果你还不了解这个函数,请看它的说明 Output Buffer Explained

posted on 2013-07-03 10:51  浩瀚孤鸿  阅读(423)  评论(0编辑  收藏  举报