How to import/include a CSS file using PHP code an

2019-01-07 21:48发布

I have googled a lot but it seems that I am doing something wrong.

I want to do this:

<?php
include 'header.php';
include'CSS/main.css';
...
?>

However, my page prints the CSS code.

Note: I want to use PHP to include the CSS file, and not use I also do you want to rename my CSS file to a PHP file as some website mentioned.

Any clues?

Many thanks.

14条回答
【Aperson】
2楼-- · 2019-01-07 22:28

You are including the CSS code as text in your PHP page. Why not just link it in the traditional fashion?

<link rel="stylesheet" href="CSS/main.css" type="text/css">
查看更多
淡お忘
3楼-- · 2019-01-07 22:31

To use "include" to include CSS, you have to tell PHP you're using CSS code. Add this to your header of your CSS file and make it main.php (or styles.css, or whatever):

header("Content-type: text/css; charset: UTF-8");

This might help with some user's connections, but it theoretically (read: I haven't tested it) adds processor overhead to your server and according to Steve Souder, because your computer can download multiple files at once, using include could be slower. If you have your CSS split into a dozen files, maybe it would be faster?

Steve's blog post: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/ Source: http://css-tricks.com/css-variables-with-php/

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-07 22:31

This is an older post, however as the info is still relevant today an additional option may help others.

  • Define a constant for the file path per Stefan's answer. The definition can be placed at the top of the PHP page itself, or within an included/required external file such as config.php. (http://php.net/manual/en/function.include.php)

  • Echo the constant in PHP tags, then add the filename directly after. That's it!
    Works for other linked files such as JavaScript as well.

<?php
define('CSS_PATH', 'template/css/'); //define CSS path 
define('JS_PATH', 'template/js/'); //define JavaScript path 
?>
<!-- Doctype should be declared, even in PHP file -->
<!DOCTYPE html> 
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo CSS_PATH; ?>main.css">
<script type="text/javascript" src="<?php echo JS_PATH; ?>main.js"></script>
</head>
<body>
</body>
</html>
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-07 22:31

The best way to do it is:

Step 1: Rename your main.css to main.php

Step 2: in your main.php add

<style> ... </style>

Step 3: include it as usual

<?php include 'main.php'; ?>

That is how i did it, and it works smoothly..

查看更多
冷血范
6楼-- · 2019-01-07 22:33

You could do this

<?php include("Includes/styles.inc"); ?>

And then in this include file, have a link to the your css file(s).

查看更多
Evening l夕情丶
7楼-- · 2019-01-07 22:34

Just put

echo "<link rel='stylesheet' type='text/css' href='CSS/main.css'>";

inside the php code, then your style is incuded. Works 100%, I tried.

查看更多
登录 后发表回答