ilumin ilumin - 3 months ago 25
CSS Question

PHP replace CSS in HTML tags

does anyone has an idea about replace css styles into style attribute on html tags
example you have css file, html file


#example { color: #CCC; font-weight: bold; }


<div id="example">Example</div>

and you will have this when you run php

<div style="color: #CCC; font-weight: bold;">Example</div>

why oh why :)

some work need inline styles for some system that doesn't support <link>, <style> or script tags


E-mail template (all of you can not insert <link>, <style>, <script> inside the email right ?),

or build HTML for insert in another system (product detail in, ...)


You probably need to use a DOM parser, take a look at SimpleHTMLDom. Here's an example:

// Assuming that it's an array of styles
// keyed by HTML element IDs or classes.
// @see
$styles = some_php_css_parser('example.css');

// Create a DOM object
$html = new simple_html_dom();

// Load HTML from a HTML file, 
// there are also other options, @see API.

// Walk through the target elements.
foreach ($html->find('blah') as $element) {
    $element->style = $styles[$element->id];

// Cache and output...

Also you need to consider caching the output, otherwise I also say so, but why oh why!