• Zia Technology Group
  • Zia Technology Group
  • Zia Technology Group
  • Zia Technology Group
  • Zia Technology Group
Zia Technology Group
407-434-0303

Inline external CSS page with PHP 0 Comments


Inline external CSS page with PHP

I was working on a little app the other day that takes snapshots of the HTML from pages and stores it in a database that I can then use to reproduce the exact page in the future even if changes had been made.

The problem I ran into was the CSS for the pages was in external pages (like it should be). So the HTML that my snapshot app produced was just linking to the external CSS page. Obviously this was a problem because even though I had a snapshot of all of the HTML if the external CSS page changed my snapshot of the page would be useless.

I did some digging and found some solutions out there that can inline the css onto the page, but I was looking for something very simple. What I came up with was to use the PHP function – file_get_contents()

Here is the really simple code I whipped up to do this:

<?php

  if($isCrawl==1) {

      $css = file_get_contents('<a href="http://www.site.com/style.css">http://www.site.com/style.css</a>');

      echo("<style>");
      echo($css);
      echo("</style>");

  }else{

      echo('<link rel="stylesheet" type="text/css" media="screen" href="<a href="http://www.site.com/style.css">http://www.site.com/style.css</a>">');

  }

?>

This is so simple. It grabs the file contents of the external CSS page and puts it into the $css variable. I then echo the style tags around the $css variable, therefore dumping all the CSS onto the page.

I wrapped it all in an if statement so that if the page is being accessed by my snapshot app (isCrawl) it inlines the CSS, if not, it keeps it in an external page.

I just wanted to share this little bit of code.

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPin on PinterestEmail this to someone