Can I use file_get_contents to load css?

12,254

Solution 1

This question was posted when I was a beginning developer. I didn't know about Sass and other easier and better ways to achieve variables in CSS. I also didn't know about browser caching.

Jeremy Karlsson answered the question in a comment. file_get_contents requires echo.

Solution 2

This does what you'd like todo, output will be your css file, use something like preg_replace if you need to have more readable content, you might want to add new lines for example, before and after { }, I tested both without preg_replace and the examples are working well with a simple css file, I did not test it with complex css files but it should work as well, I kindly ask to try it with your css files. I hope it will help you into the right direction...

<?php
$css_File = file_get_contents("css_file.css"); // Can use single quot as well...
echo '<style type="text/css">' . $css_File . '</style>'; // All php echo example
?>

OR much better example, I think this could be what you want:

<?php $css_File = file_get_contents('http://www.example.com/css_file.css'); ?>
<style type="text/css"><?php echo $css_File; ?></style><!--// your request example //-->

Solution 3

why not use

include("css_file.css");

@edit Also if you are including css file make sure to echo style tags around it

Share:
12,254
Nick Manning
Author by

Nick Manning

Web developer for inc.com.

Updated on June 15, 2022

Comments

  • Nick Manning
    Nick Manning almost 2 years

    Instead of this:

    <head>
        <link rel="stylesheet" type="text/css" href="css_file.css" />
    </head>
    

    I want to do this:

    <head>
        <style><?php file_get_contents("css_file.css");?></style>
    </head>
    

    For some reason though, the text shows up in the doc but the style is not applied. This is a two part question:

    1. Why is this not working?
    2. Is this a bad idea to do this?