2016-10-03 19 views
0

我沒有什麼問題,連接到style.php DBCSS在PHP與MySQL

<?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 {}這是不行的,但一個{}將工作。 我可以以某種方式使它工作?

+0

做過任何基本的調試,像打直接兩個版本的網址是什麼? db版本可能會輸出一些東西\在css的東西開始前,所以生成的輸出是'foo#header',而不是'#header'。 –

回答

2

如果你想從PHP使用它.php文件中像這樣生成CSS:

<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文件中使用它。您也可以從.php文件生成新的.css文件與fopen()fwrite() PHP函數,然後只是與元標記將其包括到網頁中。

從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 
?> 
+0

嘿戴夫,你能擴展(提供一個生成一個CSS文件的小例子)在你的答案? –

+2

編輯答案@GovindRai – Dave

+0

可愛!非常感謝! +1 –