2

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

css:

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

html:

<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
example:
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 amazon.com, ...)

6
  • if you have styles like .class1 .class2 { ... } class2 { .. }, it will be not easy to replace into HTML tags Commented Mar 30, 2011 at 1:57
  • 3
    the great thing about css is keeping the style separate, why do you want to reverse that? Commented Mar 30, 2011 at 2:00
  • 1
    hunting bats in daylight is far more useful than what you want to do. Commented Mar 30, 2011 at 2:05
  • 1
    a little context would be useful here. Having a separate stylesheet is preferable to inline styles. Update your question explaining why you want to do this. There is perhaps a different solution to your problem. Commented Mar 30, 2011 at 2:10
  • seperate styles from html is great but some work need that, example: email template or create html for another system that don't allow to insert style, link or script tag Commented Mar 30, 2011 at 11:19

2 Answers 2

3

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 http://www.google.com/search?q=php+css+parser
$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.
$html->load_file('test.htm');

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

Sign up to request clarification or add additional context in comments.

Comments

0

explode the css file, extract the attribute\css, str_replace the attribute with the css in the html, but why oh why.

1 Comment

glob() is my favourite based on name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.