0

I'm trying to minify the css on the fly in WordPress because if I do the minify directly my theme won't work when the comment gets removed.

First I tried to remove comments from any specified css file its working fine here is the code

<?php
$cssfile = 'style.css';//css file needed to minify
$file = fopen($cssfile, 'r');
if ($file) {
    $buffer = file_get_contents('style.css');//getting content of css file needed to minify
    $buffers = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);

    echo $buffers;
}?>

Same thing I want to do on the fly. In many tutorialS all uses ob_start() and saying about http request. I don't know these things and what they dos and also I am unable to see where they are specifying the file path like I did in the 1st line $cssfile

I think they are telling $_GET[something] for file. Is this where they mentioning the css file which needs to be minify?(Mentioning path to the css)

Can any one help me on this to do a on the fly css minify with explain of ob_start(), http request and how it works.

Bud Damyanov
  • 30,171
  • 6
  • 44
  • 52
sun
  • 1,598
  • 11
  • 26
  • 45
  • 2
    Why are you `fopen`ing the file? Also, it is not a good idea to minify CSS on-the-fly. Minifying CSS is something you do once, before you move the file to the server. – Sverri M. Olsen Dec 17 '13 at 06:31
  • possible duplicate of [how to Minify JS / CSS on the fly / runtime](http://stackoverflow.com/questions/5389822/how-to-minify-js-css-on-the-fly-runtime) – XuDing Dec 17 '13 at 06:31
  • just for checking permission i did fopen. But i used file get content inside the condition @ Sverri M. Olsen – sun Dec 17 '13 at 06:37
  • 1
    is the answer telling a third party file to minify? @XuDing – sun Dec 17 '13 at 06:41

2 Answers2

1

The can remove extra spaces from css file

try this

<?php
$search = array(
        '/\>[^\S]+/s', // strip whitespaces after tags, except space
        '/[^\S]+\</s', // strip whitespaces before tags, except space
        '/(\s)+/s'       // shorten multiple whitespace sequences
    );

    $replace = array(
        '>',
        '<',
        '\\1'
    );

    $style = preg_replace($search, $replace, $buffer = file_get_contents('style.css'));
?>

<style type="text/css"><?php echo $style; ?></style>
Girish
  • 11,907
  • 3
  • 34
  • 51
0

Okay. How about this: http://manas.tungare.name/software/css-compression-in-php

His function seems solve your problem.

XuDing
  • 1,982
  • 18
  • 27
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Pranav 웃 Dec 18 '13 at 07:07