How can I execute a PHP file before using its contents with another file?

Situation

Im mixing HTML and CSS with PHP variables so that I can manage many settings with just one configuration file. This all works fine, but I'm trying to combine and minimize CSS now. And that causes a problem.


Problem

Variables will not appear in the compressed sheet because the PHP script will not be executed. And this is because file_get_contents () converts the contents to a string.


Question

Is it possible to somehow execute the files first and then capture their contents? Or capture their contents in a different way, the way they will be executed anyway?


Files

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 ?>; } 

reduced-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"> 
+8
variables html css php
source share
3 answers

You are already 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 special here. Just added include() there ...

But it will not work as intended, if you do not, for each file:

  • Create a heredoc with all the content
  • Get him back

As an example, you can use the base stylesheet:

 <?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 broken syntax highlighting

And you're done.

No longer against ob_start() !!!

In addition, CSS comments use the syntax /* */ , // will be evaluated as an invalid CSS selector.

+1
source share

I think what you need to do is to include the file in the PHP buffer and then minimize 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; 
+4
source share

file_get_contents() will literally read the contents of the file and put the contents in a line. What you need to use include() . This will analyze the contents of the file.

+1
source share

All Articles