使用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

相關文章
相關標籤/搜索