Home Backend Development PHP Tutorial Compress php code of multiple CSS and JS files

Compress php code of multiple CSS and JS files

Jul 25, 2016 am 09:04 AM

  1. header('Content-type: text/css');
  2. ob_start("compress");
  3. function compress($buffer) {
  4. /* remove comments */
  5. $buffer = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $buffer);
  6. /* remove tabs, spaces, newlines, etc. */
  7. $buffer = str_replace(array("rn", "r", "n", "t", ' ', ' ', ' '), '', $buffer);
  8. return $buffer;
  9. }
  10. /* your css files */
  11. include('galleria.css');
  12. include('articles.css');
  13. ob_end_flush();
  14. ?>
Copy code

Instantiation: test.php

  1. test
Copy the code

2. Compress js Using jsmin class Source: http://code.google.com/p/minify/ compress.php

  1. header('Content-type: text/javascript');
  2. require 'jsmin.php';
  3. echo JSMin::minify(file_get_contents('common.js') . file_get_contents( 'common2.js'));
  4. ?>
Copy code

common.js alert('first js');

common.js alert('second js');

jsmin.php

  1. /**
  2. * jsmin.php - extended PHP implementation of Douglas Crockford's JSMin.
  3. *
  4. * </li> <li> * $minifiedJs = JSMin::minify($js); </li> <li> *
  5. *
  6. * This is a direct port of jsmin.c to PHP with a few PHP performance tweaks and
  7. * modifications to preserve some comments (see below). Also, rather than using
  8. * stdin/stdout, JSMin::minify() accepts a string as input and returns another
  9. * string as output.
  10. *
  11. * Comments containing IE conditional compilation are preserved, as are multi-line
  12. * comments that begin with "/*!" (for documentation purposes). In the latter case
  13. * newlines are inserted around the comment to enhance readability.
  14. *
  15. * PHP 5 or higher is required.
  16. *
  17. * Permission is hereby granted to use this version of the library under the
  18. * same terms as jsmin.c, which has the following license:
  19. *
  20. * --
  21. * Copyright (c) 2002 Douglas Crockford (www.crockford.com)
  22. *
  23. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  24. * this software and associated documentation files (the "Software"), to deal in
  25. * the Software without restriction, including without limitation the rights to
  26. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  27. * of the Software, and to permit persons to whom the Software is furnished to do
  28. * so, subject to the following conditions:
  29. *
  30. * The above copyright notice and this permission notice shall be included in all
  31. * copies or substantial portions of the Software.
  32. *
  33. * The Software shall be used for Good, not Evil.
  34. *
  35. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  36. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  38. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  39. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  41. * SOFTWARE.
  42. * --
  43. *
  44. * @package JSMin
  45. * @author Ryan Grove (PHP port)
  46. * @author Steve Clay (modifications + cleanup)
  47. * @author Andrea Giammarchi (spaceBeforeRegExp)
  48. * @copyright 2002 Douglas Crockford (jsmin.c)
  49. * @copyright 2008 Ryan Grove (PHP port)
  50. * @license http://opensource.org/licenses/mit-license.php MIT License
  51. * @link http://code.google.com/p/jsmin-php/
  52. */
  53. class JSMin {
  54. const ORD_LF = 10;
  55. const ORD_SPACE = 32;
  56. const ACTION_KEEP_A = 1;
  57. const ACTION_DELETE_A = 2;
  58. const ACTION_DELETE_A_B = 3;
  59. protected $a = "n";
  60. protected $b = '';
  61. protected $input = '';
  62. protected $inputIndex = 0;
  63. protected $inputLength = 0;
  64. protected $lookAhead = null;
  65. protected $output = '';
  66. /**
  67. * Minify Javascript
  68. *
  69. * @param string $js Javascript to be minified
  70. * @return string
  71. */
  72. public static function minify($js)
  73. {
  74. // look out for syntax like "++ +" and "- ++"
  75. $p = '\+';
  76. $m = '\-';
  77. if (preg_match("/([$p$m])(?:\1 [$p$m]| (?:$p$p|$m$m))/", $js)) {
  78. // likely pre-minified and would be broken by JSMin
  79. return $js;
  80. }
  81. $jsmin = new JSMin($js);
  82. return $jsmin->min();
  83. }
  84. /*
  85. * Don't create a JSMin instance, instead use the static function minify,
  86. * which checks for mb_string function overloading and avoids errors
  87. * trying to re-minify the output of Closure Compiler
  88. *
  89. * @private
  90. */
  91. public function __construct($input)
  92. {
  93. $this->input = $input;
  94. }
  95. /**
  96. * Perform minification, return result
  97. */
  98. public function min()
  99. {
  100. if ($this->output !== '') { // min already run
  101. return $this->output;
  102. }
  103. $mbIntEnc = null;
  104. if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
  105. $mbIntEnc = mb_internal_encoding();
  106. mb_internal_encoding('8bit');
  107. }
  108. $this->input = str_replace("rn", "n", $this->input);
  109. $this->inputLength = strlen($this->input);
  110. $this->action(self::ACTION_DELETE_A_B);
  111. while ($this->a !== null) {
  112. // determine next command
  113. $command = self::ACTION_KEEP_A; // default
  114. if ($this->a === ' ') {
  115. if (! $this->isAlphaNum($this->b)) {
  116. $command = self::ACTION_DELETE_A;
  117. }
  118. } elseif ($this->a === "n") {
  119. if ($this->b === ' ') {
  120. $command = self::ACTION_DELETE_A_B;
  121. // in case of mbstring.func_overload & 2, must check for null b,
  122. // otherwise mb_strpos will give WARNING
  123. } elseif ($this->b === null
  124. || (false === strpos('{[(+-', $this->b)
  125. && ! $this->isAlphaNum($this->b))) {
  126. $command = self::ACTION_DELETE_A;
  127. }
  128. } elseif (! $this->isAlphaNum($this->a)) {
  129. if ($this->b === ' '
  130. || ($this->b === "n"
  131. && (false === strpos('}])+-"'', $this->a)))) {
  132. $command = self::ACTION_DELETE_A_B;
  133. }
  134. }
  135. $this->action($command);
  136. }
  137. $this->output = trim($this->output);
  138. if ($mbIntEnc !== null) {
  139. mb_internal_encoding($mbIntEnc);
  140. }
  141. return $this->output;
  142. }
  143. /**
  144. * ACTION_KEEP_A = Output A. Copy B to A. Get the next B.
  145. * ACTION_DELETE_A = Copy B to A. Get the next B.
  146. * ACTION_DELETE_A_B = Get the next B.
  147. */
  148. protected function action($command)
  149. {
  150. switch ($command) {
  151. case self::ACTION_KEEP_A:
  152. $this->output .= $this->a;
  153. // fallthrough
  154. case self::ACTION_DELETE_A:
  155. $this->a = $this->b;
  156. if ($this->a === "'" || $this->a === '"') { // string literal
  157. $str = $this->a; // in case needed for exception
  158. while (true) {
  159. $this->output .= $this->a;
  160. $this->a = $this->get();
  161. if ($this->a === $this->b) { // end quote
  162. break;
  163. }
  164. if (ord($this->a) <= self::ORD_LF) {
  165. throw new JSMin_UnterminatedStringException(
  166. "JSMin: Unterminated String at byte "
  167. . $this->inputIndex . ": {$str}");
  168. }
  169. $str .= $this->a;
  170. if ($this->a === '\') {
  171. $this->output .= $this->a;
  172. $this->a = $this->get();
  173. $str .= $this->a;
  174. }
  175. }
  176. }
  177. // fallthrough
  178. case self::ACTION_DELETE_A_B:
  179. $this->b = $this->next();
  180. if ($this->b === '/' && $this->isRegexpLiteral()) { // RegExp literal
  181. $this->output .= $this->a . $this->b;
  182. $pattern = '/'; // in case needed for exception
  183. while (true) {
  184. $this->a = $this->get();
  185. $pattern .= $this->a;
  186. if ($this->a === '/') { // end pattern
  187. break; // while (true)
  188. } elseif ($this->a === '\') {
  189. $this->output .= $this->a;
  190. $this->a = $this->get();
  191. $pattern .= $this->a;
  192. } elseif (ord($this->a) <= self::ORD_LF) {
  193. throw new JSMin_UnterminatedRegExpException(
  194. "JSMin: Unterminated RegExp at byte "
  195. . $this->inputIndex .": {$pattern}");
  196. }
  197. $this->output .= $this->a;
  198. }
  199. $this->b = $this->next();
  200. }
  201. // end case ACTION_DELETE_A_B
  202. }
  203. }
  204. protected function isRegexpLiteral()
  205. {
  206. if (false !== strpos("n{;(,=:[!&|?", $this->a)) { // we aren't dividing
  207. return true;
  208. }
  209. if (' ' === $this->a) {
  210. $length = strlen($this->output);
  211. if ($length < 2) { // weird edge case
  212. return true;
  213. }
  214. // you can't divide a keyword
  215. if (preg_match('/(?:case|else|in|return|typeof)$/', $this->output, $m)) {
  216. if ($this->output === $m[0]) { // odd but could happen
  217. return true;
  218. }
  219. // make sure it's a keyword, not end of an identifier
  220. $charBeforeKeyword = substr($this->output, $length - strlen($m[0]) - 1, 1);
  221. if (! $this->isAlphaNum($charBeforeKeyword)) {
  222. return true;
  223. }
  224. }
  225. }
  226. return false;
  227. }
  228. /**
  229. * Get next char. Convert ctrl char to space.
  230. */
  231. protected function get()
  232. {
  233. $c = $this->lookAhead;
  234. $this->lookAhead = null;
  235. if ($c === null) {
  236. if ($this->inputIndex < $this->inputLength) {
  237. $c = $this->input[$this->inputIndex];
  238. $this->inputIndex += 1;
  239. } else {
  240. return null;
  241. }
  242. }
  243. if ($c === "r" || $c === "n") {
  244. return "n";
  245. }
  246. if (ord($c) < self::ORD_SPACE) { // control char
  247. return ' ';
  248. }
  249. return $c;
  250. }
  251. /**
  252. * Get next char. If is ctrl character, translate to a space or newline.
  253. */
  254. protected function peek()
  255. {
  256. $this->lookAhead = $this->get();
  257. return $this->lookAhead;
  258. }
  259. /**
  260. * Is $c a letter, digit, underscore, dollar sign, escape, or non-ASCII?
  261. */
  262. protected function isAlphaNum($c)
  263. {
  264. return (preg_match('/^[0-9a-zA-Z_\$\\]$/', $c) || ord($c) > 126);
  265. }
  266. protected function singleLineComment()
  267. {
  268. $comment = '';
  269. while (true) {
  270. $get = $this->get();
  271. $comment .= $get;
  272. if (ord($get) <= self::ORD_LF) { // EOL reached
  273. // if IE conditional comment
  274. if (preg_match('/^\/@(?:cc_on|if|elif|else|end)\b/', $comment)) {
  275. return "/{$comment}";
  276. }
  277. return $get;
  278. }
  279. }
  280. }
  281. protected function multipleLineComment()
  282. {
  283. $this->get();
  284. $comment = '';
  285. while (true) {
  286. $get = $this->get();
  287. if ($get === '*') {
  288. if ($this->peek() === '/') { // end of comment reached
  289. $this->get();
  290. // if comment preserved by YUI Compressor
  291. if (0 === strpos($comment, '!')) {
  292. return "n/*" . substr($comment, 1) . "*/n";
  293. }
  294. // if IE conditional comment
  295. if (preg_match('/^@(?:cc_on|if|elif|else|end)\b/', $comment)) {
  296. return "/*{$comment}*/";
  297. }
  298. return ' ';
  299. }
  300. } elseif ($get === null) {
  301. throw new JSMin_UnterminatedCommentException(
  302. "JSMin: Unterminated comment at byte "
  303. . $this->inputIndex . ": /*{$comment}");
  304. }
  305. $comment .= $get;
  306. }
  307. }
  308. /**
  309. * Get the next character, skipping over comments.
  310. * Some comments may be preserved.
  311. */
  312. protected function next()
  313. {
  314. $get = $this->get();
  315. if ($get !== '/') {
  316. return $get;
  317. }
  318. switch ($this->peek()) {
  319. case '/': return $this->singleLineComment();
  320. case '*': return $this->multipleLineComment();
  321. default: return $get;
  322. }
  323. }
  324. }
  325. class JSMin_UnterminatedStringException extends Exception {}
  326. class JSMin_UnterminatedCommentException extends Exception {}
  327. class JSMin_UnterminatedRegExpException extends Exception {}
  328. ?>
复制代码

调用示例:

复制代码


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles