InStyle

Show Me The Code

InStyle @ GitHub »
Version 0.2. Last updated 12/4/2009.

What Is InStyle?

InStyle is a script to convert embedded CSS to inline CSS for a HTML file. This is typically used for HTML e-mails. I have found numerous web pages that offer the functionality, but I had to copy and paste my HTML and CSS into their forms to get my inline CSS HTML. While it’s great for a one-time conversion, it wasn’t suitable to be a part of an automated process.

How Does InStyle Work?

  1. InStyle extracts the embedded CSS code within the <style> tags using regular expressions.
  2. InStyle creates an array where the HTML element is the key and the styles are the values.
  3. Using the Simple HTML DOM class, InStyle navigates through the HTML code and applies the appropriate styles inline.
  4. InStyle returns the HTML code with the CSS styles applied inline and the embedded styles code removed.

What Files Are Included?

  • instyle.php: PHP class that extracts embedded CSS from a HTML page and applies the CSS inline.
  • simple_html_dom.php: PHP class by S.C. Chen for navigating the HTML DOM.
  • index.php: PHP page that accepts a URL parameter of a web page with embedded code, pass it to the InStyle object, and output HTML with inline CSS.
  • README: Information about the InStyle project.

Why Not Code HTML E-mails Inline from the Start?

The whole point of CSS is to have one place to modify to adjust the styling for an entire HTML page. Back in the good old days day, you had to style each element individually, so if you wanted to change all the link colors to green, you would have to edit each one. By using embedded CSS, you can make one change and it would apply globally throughout the HTML page.

Unfortunately, e-mail clients are not standardized so their CSS capabilities are a mixed bag. So using embedded CSS styles saves time during development, but inline CSS is the way to make sure the styles get through to the e-mail client, especially GMail.

In the example included in the download, I chose to have InStyle receive the HTML code this way because I have PHP code in my HTML e-mails to save me repetitive content (e.g. Google Analytics). You can use the InStyle class to convert HTML e-mail data in a PHP variable if you need it to.

Requirements

This script is used in environments running PHP 4.3 or newer.

Acknowledgements

Because InStyle was made to run in PHP 4, I used another PHP class to navigate the DOM, Simple HTML DOM. The Simple HTML DOM is used at the final part of InStyle to apply the styles inline for each element declared in the CSS.

Open For Critique and Comments

If you find this script useful or have any suggestions, feel free to leave a comment below.

View the source or download the code from GitHub »

We'd Love to Hear from You!