【问题标题】:Concatenate css with php in link meta stylesheet在链接元样式表中将 css 与 php 连接起来
【发布时间】:2013-04-08 07:24:21
【问题描述】:

用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 站点配置提供了其他功能。

【问题讨论】:

  • 您的网址应该更像concatenator.php?files=reset,grid,commons。还有著名的 concatenator.php,如果只是一个小脚本,会爆炸files 值,检索每个文件内容以最终回显它们。

标签: php css concatenation httprequest css-frameworks


【解决方案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;

【讨论】:

  • 嗨 MatRt 感谢您的回复,但您的代码没有显示任何内容,回显为空白,我找不到问题
  • 您是否将/absolute/path/to/your/css/files/ 替换为物有所值的。?该代码非常基本,应该可以工作。你好吗&lt;link&gt;
【解决方案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;

我从this post 获得了标题部分。

【讨论】:

  • 我也通过将 $cssContent 行替换为:$cssContent .= preg_replace('/\s+/', ' ',file_get_contents($directoryOfCss . $oneFile . ".css"));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-03
  • 2015-01-28
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
相关资源
最近更新 更多