【问题标题】:Dynamically generate static CSS file which uses PHP variables动态生成使用 PHP 变量的静态 CSS 文件
【发布时间】:2014-09-23 23:59:03
【问题描述】:

我目前正在使用 PHP 变量从我的数据库中获取 CSS 值。这可以作为 php 包含,但是我想使用从数据库中提取的这些变量的输出生成一个静态 .css 文件。不知道该怎么做?

css.php

<?
$sql = $dbh->prepare("SELECT * FROM styles"); //gets background_color (#000) from DB
$sql->execute();
$result = $sql->fetch();

foreach ($result as $k => $v) { 
    $$k = $v; //makes background_color = $background_color = #000
}

<style type="text/css">
.content {
    background-color: <?=$background_color?>;
}
?>

index.php

<? require_once "css.php"; ?>

我希望使用 css.php 生成的静态 styles.css 看起来像这样:

.content { 背景颜色: ; }

【问题讨论】:

  • 我不久前处于完全相同的情况,可以找到解决方案 HERE ,如果 question 本身可以被投票,那就太好了,这样它可以作为参考

标签: php html css


【解决方案1】:

“我想生成一个静态 .css文件”

PHP:

# Generate some CSS string.
$css = '.class { color: #fff }';

# Save string to a file.
file_put_contents('/path/to/static.css', $css);

requiringcss.php 您实际上是在使用 dynamic PHP 文件来重新计算和输出每次点击时的 CSS,然后将其回显到当前文档中。由于需要访问硬盘驱动器,因此需要开销,让浏览器使用普通的 CSS 文件包含标签请求单独的文件更有效。

如果您想要动态生成的 CSS 文件,那么另一种方法是将 *.css 作为 PHP 处理特定目录。

.htaccess:

<FilesMatch "\.css$">
  SetHandler application/x-httpd-php
  Header set Content-type "text/css"
</FilesMatch>

然后您可以在“css”文件中包含 PHP 代码。请注意,与 htaccess 规则匹配的任何其他 css 文件也将被 PHP 解析,无论它们是否实际包含任何 PHP 代码。

【讨论】:

    猜你喜欢
    • 2011-05-08
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 2013-02-17
    • 2013-08-13
    • 1970-01-01
    • 2020-07-17
    相关资源
    最近更新 更多