Using PHP To Generate CSS

31st January 2008 - 3 minutes read time

Generating CSS with PHP has several benefits. For example, you can keep all of your colour declarations as PHP variables so if you need to change any colours it only takes a small edit and not a find/replace operation.

Getting PHP to generate CSS requires just two steps. The first thing to do is to open your CSS file and insert the following line at the top. This tells the browser that the file is CSS.

<?php header("Content-type: text/css"); ?>

The next step is to change the file extension on your CSS file from css to php. This will tell the server to parse the file as a PHP script and not a plain CSS file. This is a necessary step unless you have direct access to your web server and can set CSS files to be parsed as PHP, but I don't suggest that you do this as it will slow down the server when it serves normal CSS files. Once you have changed the extension you need to change the link to have the same connection.

<link rel="stylesheet" type="text/css" media="screen" href="style.php">

You are now ready to start putting PHP into your CSS files. Take the following CSS file.

  1. body{
  2. background:#fff;
  3. color:#333;
  4. }
  5. h1,h2,h3,h4{
  6. color:#00840;
  7. }

The first thing we might do is to standardise the colour declarations.

  1. <?php
  2. header("Content-type: text/css");
  3. $white = '#fff';
  4. $dkgray = '#333';
  5. $dkgreen = '#008400';
  6. ?>
  7. body{
  8. background:<?php echo $white; ?>;
  9. color:<?php echo $dkgray; ?>;
  10. }
  11. h1,h2,h3,h4{
  12. color:<?php echo $dkgreen; ?>;
  13. }

A better way to use colours is to call the variable by the function rather than the value of the colour. So using the previous example I will rename the colours so that we use the function.

  1. <?php
  2. header("Content-type: text/css");
  3. $background = '#fff';
  4. $text = '#333';
  5. $heading = '#008400';
  6. ?>
  7. body{
  8. background:<?php echo $background; ?>;
  9. color:<?php echo $text; ?>;
  10. }
  11. h1,h2,h3,h4{
  12. color:<?php echo $heading; ?>;
  13. }

 

Comments

Permalink

For variable, I will suggest an other approach, using ob_get_contents
Like this:

  1. <?php
  2. ob_start();
  3. ?>
  4.  
  5. color1 __XX__<br>
  6. color2 __XX__<br>
  7. color3 __XX__<br>
  8.  
  9. <?php for ($x=0; $x<10;$x++){ ?>
  10. data <?php echo "_".$x; ?>__YY__<br>
  11. <?php } ?>
  12.  
  13. <?php
  14. // Get data from the output buffer
  15. $data = ob_get_contents();
  16.  
  17. // Set variables
  18. $tab_strtr = array();
  19. $tab_strtr["__XX__"] = "Red";
  20. $tab_strtr["__YY__"] = "Test";
  21. $result = strtr ($data,$tab_strtr);
  22.  
  23. // Clean buffer then send the result
  24. ob_end_clean ();
  25. echo $result;
  26.  
  27. ?>

 

LAMBALLAIS Pie… (Mon, 05/31/2021 - 17:05)

Add new comment

The content of this field is kept private and will not be shown publicly.