Reputation: 2024
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.
Upvotes: 1
Views: 1159
Reputation: 796
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
Upvotes: 1
Reputation: 169
You can use id and class to save your CSS code and call whenever you want in a tag.
Upvotes: 0
Reputation: 34
I am using Emogrifier for creating HTML mail messages - and it works really good for me. Here's a link: Emogrifier
Upvotes: 0
Reputation: 64727
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/
Upvotes: 3