Php: how to compress multiple CSS and JS files

Source: Internet
Author: User
This article mainly introduces how to compress multiple CSS and JS files in php, and how to compress css files and js files by using two complete examples, for more information about how to compress multiple CSS and JS files in php, see the following example. Share it with you for your reference. The specific implementation method is as follows:

1. compress css

The code is as follows:

<? Php
Header ('content-type: text/css ');
Ob_start ("compress ");
Function compress ($ buffer ){
/* Remove comments */
$ Buffer = preg_replace ('! /\ * [^ *] * \ * + ([^/] [^ *] * \ * + )*/! ', '', $ Buffer );
/* Remove tabs, spaces, newlines, etc .*/
$ Buffer = str_replace (array ("\ r \ n", "\ r", "\ n", "\ t ",'','',''), '', $ buffer );
Return $ buffer;
}

/* Your css files */
Include('galleria.css ');
Include('articles.css ');

Ob_end_flush ();


The usage is as follows:

The code is as follows:

Test

2. compress js and use the jsmin class:

This instance Source: http://code.google.com/p/minify/

The code is as follows:

Header ('content-type: text/javascript ');
Require 'jsmin. php ';
Echo JSMin: minify (file_get_contents ('Common. js'). file_get_contents ('common2. js '));

The jsmin. php file is as follows:

The code is as follows:


<? Php
/**
* Jsmin. php-PHP implementation of Douglas Crockford's JSMin.
*
* This is pretty much a direct port of jsmin. c to PHP with just a few
* PHP-specific performance tweaks. Also, whereas jsmin. c reads from stdin and
* Outputs to stdout, this library accepts a string as input and returns another
* String as output.
*
* PHP 5 or higher is required.
*
* Permission is hereby granted to use this version of the library under
* Same terms as jsmin. c, which has the following license:
*
*--
* Copyright (c) 2002 Douglas Crockford (www.crockford.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* This software and associated documentation files (the "Software"), to deal in
* The Software without restriction, including without limitation the rights
* Use, copy, modify, merge, publish, distribute, sublicense, and/or duplicate copies
* Of the Software, and to permit persons to whom the Software is furnished to do
* So, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be encoded in all
* Copies or substantial portions of the Software.
*
* The Software shall be used for Good, not edevil.
*
* The software is provided "as is", without warranty of any kind, EXPRESS OR
* IMPLIED, including but not limited to the warranties of merchantability,
* Fitness for a participant purpose and noninfringement. IN NO EVENT SHALL
* Authors or copyright holders be liable for any claim, DAMAGES OR OTHER
* LIABILITY, whether in an action of contract, tort or otherwise, arising from,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* SOFTWARE.
*--
*
* @ Package JSMin
* @ Author Ryan Grove
* @ Copyright 2002 Douglas Crockford (Jsmin. c)
* @ Copyright 2008 Ryan Grove (PHP port)
* @ Copyright 2012 Adam Goforth (Updates)
* @ License http://opensource.org/licenses/mit-license.php MIT License
* @ Version 1.1.2 (2012-05-01)
* @ Link https://github.com/rgrove/jsmin-php
*/
Class JSMin {
Const ORD_LF = 10;
Const ORD_SPACE = 32;
Const ACTION_KEEP_A = 1;
Const ACTION_DELETE_A = 2;
Const ACTION_DELETE_A_ B = 3;
Protected $ a = '';
Protected $ B = '';
Protected $ input = '';
Protected $ inputIndex = 0;
Protected $ inputLength = 0;
Protected $ lookAhead = null;
Protected $ output = '';
// -- Public Static Methods --------------------------------------------------
/**
* Minify Javascript
*
* @ Uses _ construct ()
* @ Uses min ()
* @ Param string $ js Javascript to be minified
* @ Return string
*/
Public static function minify ($ js ){
$ Jsmin = new JSMin ($ js );
Return $ jsmin-> min ();
}
// -- Public Instance Methods ------------------------------------------------
/**
* Constructor
*
* @ Param string $ input Javascript to be minified
*/
Public function _ construct ($ input ){
$ This-> input = str_replace ("\ r \ n", "\ n", $ input );
$ This-> inputLength = strlen ($ this-> input );
}
// -- Protected Instance Methods ---------------------------------------------
/**
* Action -- do something! What to do is determined by the $ command argument.
*
* Action treats a string as a single character. Wow!
* Action recognizes a regular expression if it is preceded by (or, or =.
*
* @ Uses next ()
* @ Uses get ()
* @ Throws JSMinException If parser errors are found:
*-Unterminated string literal
*-Unterminated regular expression set in regex literal
*-Unterminated regular expression literal
* @ Param int $ command One of class constants:
* ACTION_KEEP_A Output A. Copy B to A. Get the next B.
* ACTION_DELETE_A Copy B to A. Get the next B. (Delete ).
* ACTION_DELETE_A_ B Get the next B. (Delete B ).
*/
Protected function action ($ command ){
Switch ($ command ){
Case self: ACTION_KEEP_A:
$ This-> output. = $ this->;
Case self: ACTION_DELETE_A:
$ This-> a = $ this-> B;
If ($ this-> a = "'" | $ this-> a = '"'){
For (;;){
$ This-> output. = $ this->;
$ This-> a = $ this-> get ();
If ($ this-> a ===$ this-> B ){
Break;
}
If (ord ($ this-> a) <= self: ORD_LF ){
Throw new JSMinException ('unterminated string literal .');
}
If ($ this-> a === '\\'){
$ This-> output. = $ this->;
$ This-> a = $ this-> get ();
}
}
}
Case self: ACTION_DELETE_A_ B:
$ This-> B = $ this-> next ();
If ($ this-> B === '/'&&(
$ This-> a = '(' | $ this-> a = ',' | $ this-> a = '|
$ This-> a = ':' | $ this-> a = '[' | $ this-> a = '! '|
$ This-> a ===' & '| $ this-> a ===' |' | $ this-> a === '? '|
$ This-> a ===' {'| $ this-> a ===='}' | $ this-> a ==='; '|
$ This-> a = "\ n ")){
$ This-> output. = $ this-> a. $ this-> B;
For (;;){
$ This-> a = $ this-> get ();
If ($ this-> a === '['){
/*
Inside a regex [...] set, which MAY contain a '/' itself. Example: mootools Form. Validator near line 460:
Return Form. Validator. getValidator ('isempty'). test (element) | (/^ (? [A-z0-9! # $ % & '* +/=? ^ _ '{| }~ -] \.?) {0, 63} [a-z0-9! # $ % & '* +/=? ^ _ '{| }~ -] @ (? :(? : [A-z0-9] (? : [A-z0-9-] {} [a-z0-9])? \.) * [A-z0-9] (? : [A-z0-9-] {} [a-z0-9])? | \[(? :(? : 25 [0-5] | 2 [0-4] [0-9] | [01]? [0-9] [0-9]?) \.) {3 }(? : 25 [0-5] | 2 [0-4] [0-9] | [01]? [0-9] [0-9]?) \]) $/I). test (element. get ('value '));
*/
For (;;){
$ This-> output. = $ this->;
$ This-> a = $ this-> get ();
If ($ this-> a ==='] ') {
Break;
} Elseif ($ this-> a === '\\'){
$ This-> output. = $ this->;
$ This-> a = $ this-> get ();
} Elseif (ord ($ this-> a) <= self: ORD_LF ){
Throw new JSMinException ('unterminated regular expression set in regex literal .');
}
}
} Elseif ($ this-> a === '/'){
Break;
} Elseif ($ this-> a === '\\'){
$ This-> output. = $ this->;
$ This-> a = $ this-> get ();
} Elseif (ord ($ this-> a) <= self: ORD_LF ){
Throw new JSMinException ('unterminated regular expression literal .');
}
$ This-> output. = $ this->;
}
$ This-> B = $ this-> next ();
}
}
}
/**
* Get next char. Convert ctrl char to space.
*
* @ Return string | null
*/
Protected function get (){
$ C = $ this-> lookAhead;
$ This-> lookAhead = null;
If ($ c === null ){
If ($ this-> inputIndex <$ this-> inputLength ){
$ C = substr ($ this-> input, $ this-> inputIndex, 1 );
$ This-> inputIndex + = 1;
} Else {
$ C = null;
}
}
If ($ c = "\ r "){
Return "\ n ";
}
If ($ c = null | $ c = "\ n" | ord ($ c)> = self: ORD_SPACE ){
Return $ c;
}
Return '';
}
/**
* Is $ c a letter, digit, underscore, dollar sign, or non-ASCII character.
*
* @ Return bool
*/
Protected function isAlphaNum ($ c ){
Return ord ($ c)> 126 | $ c ===' \ '| preg_match ('/^ [\ w \ $] $/', $ c) = 1;
}
/**
* Perform minification, return result
*
* @ Uses action ()
* @ Uses isAlphaNum ()
* @ Uses get ()
* @ Uses peek ()
* @ Return string
*/
Protected function min (){
If (0 = strncmp ($ this-> peek (), "\ xef", 1 )){
$ This-> get ();
$ This-> get ();
$ This-> get ();
}
$ This-> a = "\ n ";
$ This-> action (self: ACTION_DELETE_A_ B );
While ($ this->! = Null ){
Switch ($ this-> ){
Case '':
If ($ this-> isAlphaNum ($ this-> B )){
$ This-> action (self: ACTION_KEEP_A );
} Else {
$ This-> action (self: ACTION_DELETE_A );
}
Break;
Case "\ n ":
Switch ($ this-> B ){
Case '{':
Case '[':
Case '(':
Case '+ ':
Case '-':
Case '! ':
Case '~ ':
$ This-> action (self: ACTION_KEEP_A );
Break;
Case '':
$ This-> action (self: ACTION_DELETE_A_ B );
Break;
Default:
If ($ this-> isAlphaNum ($ this-> B )){
$ This-> action (self: ACTION_KEEP_A );
}
Else {
$ This-> action (self: ACTION_DELETE_A );
}
}
Break;
Default:
Switch ($ this-> B ){
Case '':
If ($ this-> isAlphaNum ($ this-> )){
$ This-> action (self: ACTION_KEEP_A );
Break;
}
$ This-> action (self: ACTION_DELETE_A_ B );
Break;
Case "\ n ":
Switch ($ this-> ){
Case '}':
Case ']':
Case ')':
Case '+ ':
Case '-':
Case '"':
Case "'":
$ This-> action (self: ACTION_KEEP_A );
Break;
Default:
If ($ this-> isAlphaNum ($ this-> )){
$ This-> action (self: ACTION_KEEP_A );
}
Else {
$ This-> action (self: ACTION_DELETE_A_ B );
}
}
Break;
Default:
$ This-> action (self: ACTION_KEEP_A );
Break;
}
}
}
Return $ this-> output;
}
/**
* Get the next character, skipping over comments. peek () is used to see
* If A'/'is followed by A'/'or '*'.
*
* @ Uses get ()
* @ Uses peek ()
* @ Throws JSMinException On unterminated comment.
* @ Return string
*/
Protected function next (){
$ C = $ this-> get ();
If ($ c = '/'){
Switch ($ this-> peek ()){
Case '/':
For (;;){
$ C = $ this-> get ();
If (ord ($ c) <= self: ORD_LF ){
Return $ c;
}
}
Case '*':
$ This-> get ();
For (;;){
Switch ($ this-> get ()){
Case '*':
If ($ this-> peek () === '/'){
$ This-> get ();
Return '';
}
Break;
Case null:
Throw new JSMinException ('unterminated comment .');
}
}
Default:
Return $ c;
}
}
Return $ c;
}
/**
* Get next char. If is ctrl character, translate to a space or newline.
*
* @ Uses get ()
* @ Return string | null
*/
Protected function peek (){
$ This-> lookAhead = $ this-> get ();
Return $ this-> lookAhead;
}
}
// -- Exceptions ---------------------------------------------------------------
Class JSMinException extends Exception {}
?>

I hope this article will help you with php programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.