用PHP以一种简便的方式来压缩你的CSS文件,不需要命名你的.css文件和.php文件。
当前有许多方法需要将.css文件重命名成.php文件,然后在所有PHP文件中放置压缩代码。
本代码的优点:
不需要重命名CSS并且只需要一个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("rn", "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(http://www.phpcodebase.com/php-output-buffering-explained/)。