I’m mixing HTML & CSS with PHP variables, so that I can manage a lot of settings with just one config file. This is all working fine, but I’m trying to merge and minify the CSS now. And this causes a problem.
The variables won’t be echoed into the compressed sheet because the PHP script won't be executed. And that is because file_get_contents() converts the content into a string.
Is it in some way possible to execute the files first, and then grab their contents? Or grab their contents in another way, a way that they still will be executed?
config.php
$priColor = '#000';
base-stylesheet.php
/* CSS header defined */
/* config.php included */
body{
background-color: <?= $priColor ?>;
}
specific-stylesheet.php
/* CSS header defined */
/* config.php included */
.site-specific-element{
background-color: <?= $priColor ?>;
}
minified-stylesheets.php
// Set files that must be minified
$cssFiles = array(
"base-styleseet.php",
"specific-stylesheet.php"
);
// Get those files
$buffer = "";
foreach ($cssFiles as $cssFile) {
$buffer .= file_get_contents($cssFile);
}
// Minify and echo them
minifyCSS($buffer);
echo $buffer;
index.php
<link rel="stylesheet" href="minified-stylesheets.php">
I think what you need to do is include the file into a PHP buffer and then minify the buffer
// Set files that must be minified
$cssFiles = array(
"base-styleseet.php",
“specific-stylesheet.php"
);
// Get those files
ob_start();
foreach ($cssFiles as $cssFile) {
include($cssFile);
}
// Minify and echo them
$css = minifyCSS(ob_get_clean());
echo $css;
You already are familiar with the ob_start()
method.
But I will show a better alternative (and faster):
Your main file:
$cssFiles = array(
"base-styleseet.php",
"specific-stylesheet.php"
);
$buffer = "";
foreach ($cssFiles as $cssFile) {
$buffer .= include($cssFile);
}
minifyCSS($buffer);
echo $buffer;
Well, nothing much here. Just added a include()
there...
But it won't work as intended, unless you do like this, for every file:
Using the base stylesheet as an example:
<?php
//remember to escape the { chars
return <<<CSS
/* CSS header defined */
/* config.php included */
body\{
background-color: $priColor;
/* with an array */
background-image: url('{$images['print']}');
/* or */
background-image: url('$images[print]');
\}
CSS;
* Ignore the broken syntax highlight
And you are done.
No more nasty ob_start()
!!!
Also, CSS comments use the /* */
syntax, //
will be evaluated as an invalid CSS selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With