Question

What is the way to concatenate multiple css files into one line with php?

I want to reduce the following ..

<link href="reset.css" rel="stylesheet" type="text/css" media="screen">
<link href="grid.css" rel="stylesheet" type="text/css" media="screen">
<link href="commons.css" rel="stylesheet" type="text/css" media="screen">

into

<link href="concatenator.php+reset.css+grid.css+commons.css" rel="stylesheet" type="text/css" media="screen">

the result one css or html file with all stylesheet inside

This method reduce the http requests, and have other features for designer and developer with use dinamyc sites configurations.

Was it helpful?

Solution

The code posted by MatRt is close, but is using + signs instead of . signs for the appending and it doesn't seem to actually send the CSS to the page, even though it will print the CSS.

I managed to get the code supplied here working with a small tweak to it. Here it is:

<?php

// Check the parameter and stop if there is no files param
if (empty($_GET['files']))
    die();

// Retrieve the list of files
$files = explode(",", $_GET['files']);
$directoryOfCss = 'C:\xampplite\htdocs\path\to\my\folder\css\\';
$cssContent = "";

// Loop on all potential file and try to retrieve its content
foreach($files as $oneFile)
{
	//echo $directoryOfCss . $oneFile . ".css";
    if (file_exists($directoryOfCss . $oneFile . ".css")){
    	//echo $directoryOfCss . $oneFile . ".css<br>";
        $cssContent .= file_get_contents($directoryOfCss . $oneFile . ".css");
    }
}

// Finally echo the total content of CSS
header("Content-Type: text/css"); 
header("X-Content-Type-Options: nosniff");
header("Content-Type: text/css;X-Content-Type-Options: nosniff;");
echo $cssContent;

I got the headers part from this post.

OTHER TIPS

Your URL should be more like

concatenator.php?files=reset,grid,commons

Note: you can chose other separator if you don't like the ,

And the famous concatenator.php could be like

<?php

// Check the parameter and stop if there is no files param
if (empty($_GET['files']))
    die();

// Retrieve the list of files
$files = explode(",", $_GET['files']);
$directoryOfCss = "/absolute/path/to/your/css/files/";
$cssContent = "";

// Loop on all potential file and try to retrieve its content
foreach($files as $oneFile)
{
    if (file_exists($directoryOfCss + $oneFile + ".css"))
        $cssContent += file_get_contents($directoryOfCss + $oneFile + ".css");
}

// Finally echo the total content of CSS
echo $cssContent;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top