Can I use file_get_contents to load css?

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?

Answers


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.


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 //-->

why not use

include("css_file.css");

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


Need Your Help

how to decrypt the track data using 3DES DUKPT

encryption cryptography ansi 3des credit-card-track-data

I am working with a piece of hardware that encrypts data using Triple Des DUKPT (ANSI Standard). I have access to the KSN and the encrypted track2 data from this I need the data to be decrypted.

Forms authentication problems when migrating asp.net from WebForms to MVC

c# jquery asp.net asp.net-mvc forms-authentication

I am upgrading my project from asp.net web forms to MVC4, step by step. In the first step I changed the login page and few other pages. I am using forms authentication, with my own logic (no member...