How to import/include a CSS file using PHP code and not HTML code?
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.
You have to surround the CSS with a
<?php include 'header.php'; ?> <style> <?php include 'CSS/main.css'; ?> </style> ...
include works fine with
.css ending too. In this way you can even use PHP in your CSS file. That can be really helpful to organize e.g. colors as variables.
Read more... Read less...
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">
you can use:
<?php $css = file_get_contents('CSS/main.css'); echo $css; ?>
and assuming that css file doesn't have it already, wrap the above in:
<style type="text/css"> ... </style>
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/
<?php define('CSSPATH', 'template/css/'); //define css path $cssItem = 'style.css'; //css item to display ?> <html> <head> <title>Including css</title> <link rel="stylesheet" href="<?php echo (CSSPATH . "$cssItem"); ?>" type="text/css"> </head> <body> ... ... </body> </html>
YOUR CSS ITEM IS INCLUDED
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!