1

Anyone know of a PHP method, code snippet or project that I can use or start with to take a HTML input and remove the <style> tag but apply all the styles to each element they were intended for?

Example Input:

<html>
    <head>
        <style>
            body {
                font-size: 10px;
            }
            td {
                font-size: 8px;
            }
        </style>
    </head>
    <body>
        <!--This is my table with smaller text: -->
        <table>
            <tr><td>this text is:</td><td>8px</td></tr>
        </table>
    </body>
</html>

Desired output:

<html>
    <head>
    </head>
    <body style="font-size: 10px;">
    <!-- This is my table with smaller text: -->
        <table>
            <tr><td style="font-size: 8px;">this text is:</td><td style="font-size: 8px;">8px</td></tr>
        </table>
    </body>
</html>

Why? I want my app to include original emails with replies without the original message styles messing with the format of the reply. I'm guessing this is the way forward for me because when you view the source of a reply in Outlook, it seems to use this method.

1
  • Why do you want to remove style tag? and is it necessary? then use inline CSS. Commented Jan 19, 2017 at 4:31

4 Answers 4

3
+50

https://github.com/tijsverkoyen/CssToInlineStyles should do the trick. The code would look like this:

use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;

$cssToInlineStyles = new CssToInlineStyles();

$css = "body {
            font-size: 10px;
        }
        td {
            font-size: 8px;
        }";
$html = "
    <body>
    <!--This is my table with smaller text: -->
      <table>
        <tr><td>this text is:</td><td>8px</td></tr>
      </table>
    </body>
";
echo $cssToInlineStyles->convert(
    $html,
    $css
);

If you'd rather use an online tool there is also http://premailer.dialect.ca/

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

Comments

1

What you're looking is a style inliner, that's often used on HTML email development, here you have some tools:

Depending on your apps code, you could find some library to do so... if you want to build your own.... maybe the npm package can serve you as guide.

Hope this helps

1 Comment

with that info, you could consider answering my other question with a very similar answer ;) stackoverflow.com/questions/41712741/…
0

I am using Emogrifier for creating HTML mail messages - and it works really good for me. Here's a link: Emogrifier

Comments

0

You can use id and class to save your CSS code and call whenever you want in a tag.

Comments

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.