我对 style.php 到 db 的连接没有什么问题
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
header("Content-type: text/css; charset: UTF-8");
$Color = "#000000";
$Test = "#555000";
?>
#header {
background-color: <?php echo $Test; ?>;
width: 500px;
height: 500px;
}
a{
color: <?php echo $Color; ?>;
}
此代码运行良好。 当我做这样的事情时:
<?php
header("Content-type: text/css; charset: UTF-8");
$Color = "#000000";
$Test = "#555000";
?>
#header {
background-color: <?php echo $Test; ?>;
width: 500px;
height: 500px;
}
a{
color: <?php echo $Color; ?>;
}
这里 #header{} 这行不通,但 {} 可以。 我能以某种方式让它发挥作用吗?
最佳答案
如果你想从 PHP 生成 CSS,请像这样在 .php
文件中使用它:
<html>
<body>
<?php
$Color = "#000000";
$Test = "#555000";
?>
<style>
#header {
background-color: <?php echo $Test; ?>;
width: 500px;
height: 500px;
}
a{
color: <?php echo $Color; ?>;
}
</style>
</body>
</html>
不要在.css
文件中使用它。您还可以使用 fopen()
和 fwrite()
PHP 函数从 .php
文件生成新的 .css
文件然后使用元标记将其包含到网页中。
从 PHP 创建 .css
文件
<?php
$Color = "#000000";
$Test = "#555000";
$css = '#header {
background-color: '.$Test.';
width: 500px;
height: 500px;
}
a {
color: '.$Color.';
}';
$myfile = fopen("generated_style.css", "w") or die("Unable to open file!"); // Open file
fwrite($myfile, $css); // Write CSS
fclose($myfile); // Close file
?>
关于php - PHP 中的 CSS 与 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39838366/