使用PHP来压缩CSS文件

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

那让咱们看看是怎么实现,首先建立一个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 Explainedcss

相关文章
相关标签/搜索