1

用php将多个css文件串联成一行的方法是什么?

我想减少以下..

<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">

进入

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

结果是一个包含所有样式表的 css 或 html 文件

这种方法减少了 http 请求,并为设计人员和开发人员使用 dinamyc 站点配置提供了其他功能。

4

2 回答 2

2

MatRt 发布的代码很接近,但使用 + 符号而不是 . 附加标志,它似乎并没有实际将 CSS 发送到页面,即使它会打印 CSS。

我设法让这里提供的代码对其进行了一些小调整。这里是:

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

我从这篇文章中得到了标题部分。

于 2014-11-12T11:36:45.103 回答
1

您的网址应该更像

concatenator.php?files=reset,grid,commons

注意:如果您不喜欢,您可以选择其他分隔符,

著名的concatenator.php可能就像

<?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;
于 2013-04-16T02:31:59.243 回答