缝合css文件并缩小onthefly

时间:2011-07-30 16:35:25

标签: php css

我缝合css文件以提高性能。

现在我想要包含一个minify函数,如下所示。我该如何加入这个?

function minify( $css ) {
    $css = preg_replace( '#\s+#', ' ', $css );
    $css = preg_replace( '#/\*.*?\*/#s', '', $css );
    $css = str_replace( '; ', ';', $css );
    $css = str_replace( ': ', ':', $css );
    $css = str_replace( ' {', '{', $css );
    $css = str_replace( '{ ', '{', $css );
    $css = str_replace( ', ', ',', $css );
    $css = str_replace( '} ', '}', $css );
    $css = str_replace( ';}', '}', $css );

    return trim( $css );
}

针对缝合的代码:

<?php
$filename = $_GET['files']; 
// validate that $filename is set, contains only legal characters  
// and does not contain multiple dots (potential sign of trouble) 
if (!$filename || 
        !preg_match('/^([\.\-\_a-z0-9]*)$/i', $filename) || 
        preg_match('/([\.]{2,})/', $filename))     
    exit(); 

// we're sending CSS back to the browser 
header('Content-Type: text/css'); 

$files = explode('-', $filename, 15); 

// we're also writing CSS to a subdirectory "cache" 
// the filename will be the hyphen-delimited value  
// of $filename 
$cachefile = @fopen('cache/'. $filename, 'w'); 

// loop through, read each file, and stitch them together
foreach ($files AS $file) {
    $fcontents = null;     
    if ($cssfile = fopen($file, 'r')) {         
        $fcontents = fread($cssfile, filesize($file)) ."\n";         
        fclose($cssfile);     
    }

    // if we read something, write it and send it to browser     
    if ($fcontents) {
        fwrite($cachefile, $fcontents, strlen($fcontents));
        echo $fcontents;     
    }     
} 

// all done 
fclose($cachefile);
?>

2 个答案:

答案 0 :(得分:6)

如果你愿意,已经有一个库可以做到这一点

http://code.google.com/p/cssmin/

用法: CSSMin::minify($css);

答案 1 :(得分:0)

请看https://github.com/web-developer/Resource-Handler。这允许你将所有的css变为1。它还可以压缩,缩小甚至缓存你的CSS。它也适用于你的js。这需要最少的配置或麻烦,不像其他一些建议。

资源处理程序