如何用PHP替换file_get_contents中的变量生成css文件



我正在用php开发我自己的cms,并想实现一个颜色选择器来从后端更改颜色,但问题是我不知道如何用新的颜色值生成css,当我打开style.css时,变量不会改变。

我做错了什么?这是正确的方法吗?

生成.php

$Color = "#000000";
$Background = "#555000";
$cssFile = file_get_contents('style.css');
$myfile = fopen("style.css", "w") or die("Unable to open file!");
fwrite($myfile, $cssFile);
fclose($myfile);

style.css

#header {
background-color: $Background;
width: 500px;
height: 500px;
}
a {
color: $Color;
}

创建一个示例文件:style.css.txt

#header {
background-color: {php_background};
width: 500px;
height: 500px;
}
a {
color: {php_color};
}

generate.php

<?php
/* -------------------- */
$color      = "#000000";
$background = "#555000";
/* -------------------- */
$cssFile = file_get_contents('style.css.txt');
/* -------------------- */
$cssFile = str_replace('{php_background}', $background, $cssFile);
$cssFile = str_replace('{php_color}', $color, $cssFile);
/* -------------------- */
$handler = fopen("style.css", "w") or die("Unable to open file!");
/* -------------------- */
fwrite($handler, $cssFile);
fclose($handler);
/* -------------------- */

它将创建新的style.css文件并插入新的颜色设置:

#header {
background-color: #555000;
width: 500px;
height: 500px;
}
a {
color: #000000;
}

使用php字符串替换。。https://www.php.net/manual/en/function.str-replace.php

$str=file_get_contents('style.css');
//replace something in the file string - this is a VERY simple example
$str=str_replace("color:blue;", "color:red",$str);
//write the entire string
file_put_contents('style.css', $str);

最新更新