CSS minificar con extensión PHP

Cómo puedo minify a .php file with CSS contents?
Currently I get a 400 error.

Normally I call minify like this

<link rel="stylesheet" type="text/css" 
       href="{$workspace}/min/f=workspace/css/common.css" />

EDITAR

The answer is changing the minify source code, but what is the change I should make?

In other words.. this call should work and process as CSS..

<link rel="stylesheet" type="text/css" 
      href="{$workspace}/min/f=workspace/css/common.php" />

Maybe with an optional declaration?

<link rel="stylesheet" type="text/css" 
href="{$workspace}/min/f=workspace/css/common.php&type=css" />

EDITAR

I created the project here @ https://github.com/into/less-less

preguntado el 28 de agosto de 11 a las 01:08

Is there a specific reason why you're after runtime minifying? Why incur the extra server overhead of doing this (even if you're caching it, it's still at least a database query or file read that's unnecessary.. -

extra server overhead? it makes zero impact -

Maybe I'm misunderstanding what you're trying to achieve.. You have CSS contents in a PHP file that you want to minify on the fly, correct? -

Then there is server overhead implicitly connected with your proposed solution. You'll be running code through the spawned PHP process to minify your scripts. I have yet to see a situation where you can't write a quick build script using YUI compressor, minify, etc. that generates what you need. Then, you serve the files via web server without having it touch your PHP process. -

Of course, that's just me.. Always looking easy win cycle sparing here 'n there ;) -

4 Respuestas

Your CSS+PHP script outputs CSS only after it's requested from a server and parsed by PHP. Minify reads files directly from the server, skipping the HTTP request. So I see two paths:

  1. Less optimal [?]: make minify download the CSS like this:

    <link rel="stylesheet" type="text/css" href="{$workspace}/min/f=http://site.com/workspace/css/common.php" />
    
  2. Include Minify lib in your common.php file and use its clases (p.ej Minify_CSS) before output. Something like echo Minify_CSS::minify($css)

Actualizar:

Your example repo contains a strange file name which wouldn't let me pull/push appropriately, so here's the changed report.php:

<pre>
<strong>LESS in</strong>
<?= file_get_contents('workspace/less/common.less') ?>
- - - - -
<strong>CSS out</strong>
<?
require 'workspace/php/lessc.inc.php';
$lc = new lessc();
$contents = file_get_contents( 'workspace/less/common.less' );
$css = $lc->parse( $contents );
echo $css;
?>
<strong>Minified</strong>
<?php
require 'workspace/min/lib/Minify/CSS/Compressor.php';
echo Minify_CSS_Compressor::process($css);
?>
</pre>

Respondido el 04 de Septiembre de 11 a las 17:09

Could you please write out option 2? I'm not that familiar with classes :( // ideally it would be a zip with minify that i could download.. that would definitely earn you the bounty. Thank you so much ! - Kirk Strobeck

Could you please write out option 2? I'm not that familiar with classes :( // ideally it would be a zip with minify that i could download.. that would definitely earn you the bounty. Thank you so much ! - Kirk Strobeck

Check the edited answer, the comment box does not work well for code. - Andrés

No, you can't easily do it as minify heavily depends on file extensions (css,js,?). For example it is used to determine what HTTP headers send to client(application/x-javascript,text/css,?), what minifier class to use, is this file safe to parse etc.

But I'm almost certain that this situation can be avoided. Could you please describe why exactly you want to do this?

If you insist on doing it this way I can propose a few dirty hacks to make it work, but it requires changing minify's source code so I don't really know if that is a good idea.

Upd:

There is no nice way to change this source: it has really bad structure. In minify v2.1.3 you can simply change the following:

Path: lib/Minify/Controller/Base.php##Minify_Controller_Base::_fileIsSafe()

return in_array(strrev($revExt), array('js', 'css', 'html', 'txt'));

->

return in_array(strrev($revExt), array('js', 'css', 'html', 'txt', 'php'));

Path: lib/Minify/Controller/MinApp.php##Minify_Controller_MinApp::setupSources()

preg_match('/^[^,]+\\.(css|js)(?:,[^,]+\\.\\1)*$/', $_GET['f'])

->

preg_match('/^[^,]+\\.(css|js|php)(?:,[^,]+\\.\\1)*$/', $_GET['f'])

Path: lib/Minify/##Minify_Source::__construct()

case 'css'  : $this->contentType = 'text/css';

->

case 'php': case 'css': $this->contentType = 'text/css';

and everything will work, but you must set $min_serveOptions['minApp']['allowDirs'] in configuration carefully as any user may be able to view any php file from this directories.

Respondido 31 ago 11, 17:08

I updated my post, it should work and I doubt it could be made better as source code is structured badly, but again, I highly discourage you from doing it this way. - XzKto

Usar CSS Min, you are freely could do whatsoever and you could also "processing" your stlyesheet in php script, then minify it on the fly : its DEAD simple to do that, and guess what, it just A SINGLE FILE.

Another way is, dont use any PHP script to process or doing some logical at your css file, instead, you could have separated small css file then you just load whatever you want by building new cache file or just combine and output the link tag.

However, if you are now have something like this in your common.php (php file/script that outputing the css, yes?)

<?php 
    $style = '';
    $bodyStyle =  'body {
            background-color: #000;
            margin: 40px;
            font: 13px/20px normal Helvetica, Arial, sans-serif;
            color: #fff;
            }';
    // I assumed you are about proccesing something here..
    // ...
    // Then you merged all style into one string, and output it as css file
    $style = $bodyStyle + $otherStyle + $whateverStyle;
    header('Content-Type: text/css');
    echo $style;
?>

And you still want to make your app bloated and make your code more unreadable (wait, there still more...), also want to modify Minify class/lib to minify and cache you pseudo-css-php, then you need to "hacking" the source as follow :

  • lib/Minify/Controller/Base.php : 135, change to :

    return in_array(strrev($revExt), array('js', 'css', 'html', 'txt', 'php'));

  • lib/Minify/Controller/MinApp.php : 75, change to :

    ! preg_match('/^[^,]+\\.(css|js|php)(?:,[^,]+\\.\\1)*$/', $_GET['f'])

  • lib/Minify/Source.php, change several things :

Add one variable as a PHP flag, in , after line 41 perhaps

/**
 * @var bool
 */
public $isPHP = FALSE;

In same file, at line : 67, add a condition :

case 'php'  : $this->isPHP = TRUE;
              $this->contentType = 'text/css';
              break;

Last, replace getContent() function, into :

public function getContent()
{
    if($this->isPHP)
    {
        include($this->filepath);
    }
    else 
    {
        $content = (null !== $this->filepath)
                ? file_get_contents($this->filepath)
                : ((null !== $this->_content)
                    ? $this->_content
                    : call_user_func($this->_getContentFunc, $this->_id)
                );
    }

    // remove UTF-8 BOM if present
    return (pack("CCC",0xef,0xbb,0xbf) === substr($content, 0, 3))
        ? substr($content, 3)
        : $content;
}
  • You also need to change your common.php into Minify spec, so now, your common.php should looks like :

You need to put all your stylesheet as string and assign it into $content variable

<?php 
    //$style = '';
    $bodyStyle =  'body {
            background-color: #000;
            margin: 40px;
            font: 13px/20px normal Helvetica, Arial, sans-serif;
            color: #fff;
            }';
    // I assumed you are about proccesing something here..
    // ...
    // Then you merged all style into one string, and output it as css file
    // $style = $bodyStyle + $otherStyle + $whateverStyle;
    // header('Content-Type: text/css');
    // echo $style;
    $content = $bodyStyle + $otherStyle + $whateverStyle;
?>

Respondido 31 ago 11, 22:08

Yes, there is one and it works pretty well:

https://github.com/c9s/pecl-cssmin

The API is pretty simple:

<?php
echo cssmin("body { .... } .rule {  } .rule2 { color: #fff; }");

Respondido 24 Oct 14, 11:10

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.