使用PHP创建一个外部动态生成的CSS文件。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用PHP创建一个外部动态生成的CSS文件。相关的知识,希望对你有一定的参考价值。

One other thing to note, is that the php generated css file can make use of query parameters, for instance:

<link rel="stylesheet" href="base.css.php?type=alternate" type="text/css" >

in your PHP file you can use the variable:

if ($_GET['type'] == 'alternate'){
// set some options etc. ....
}
  1. -- This is a very easy way to create a dynamically generated CSS file in PHP
  2. --
  3. -- The important parts of the code below:
  4. -- 1. note that the PHP generated CSS file must start out with
  5. -- header('Content-type: text/css');
  6. --
  7. -- 2. The file name should end in .php not .css , since this is a PHP file.
  8. --
  9. -- Why this works: when the CSS file is requested by the remote server, the
  10. -- server sees the .php extension and preprocesses it before sending it to
  11. -- the client browser. Since the PHP file sets the Content-type as text/css
  12. -- the client browser treats it like a CSS file.
  13. --
  14. -- Code written by dbug13(Jamie Allison)
  15.  
  16. ----- Begin Dynamic CSS file: base.css.php -----
  17. <?php
  18. header('Content-type: text/css');
  19.  
  20. // Try changing the variables below, and refresh your html file.
  21. $bg_color = "purple";
  22. $base_font="Verdana,Arial,sans";
  23. ?>
  24. body{
  25. font-family: <?php echo $base_font; ?>;
  26. background-color: <?php echo $bg_color; ?>;
  27.  
  28. }
  29. ?>
  30. ----- End Dynamic CSS file
  31.  
  32. ----- Begin HTML file that uses above CSS file: index.html -----
  33. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  34. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  35.  
  36. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  37. <head>
  38. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  39. <!-- Include the dynamic CSS file -->
  40. <link rel="stylesheet" href="base.css.php" type="text/css" media="screen" title="no title" charset="utf-8">
  41. <title>untitled</title>
  42.  
  43. </head>
  44.  
  45. <body>
  46.  
  47. <h1>Hello World</h1>
  48.  
  49. </body>
  50. </html>
  51. ----- End HTML file -----

以上是关于使用PHP创建一个外部动态生成的CSS文件。的主要内容,如果未能解决你的问题,请参考以下文章

使用 PHP 从外部公共文件夹提供 css 图像

如何动态加载外部CSS与JS文件

如何动态加载外部 CSS 文件?

php简介

使用 JavaScript 或 PHP 动态生成 CSS 网格

PHP代码生成