Converting HTML to Plain Text in PHP
Using TinyMCE to render content on a web interface is standard practice, but sending that same content via email requires a different approach. Email clients struggle with complex DOM structures, inline styles, and even basic entities like . While libraries like html2text offer a starting point, their lack of robust UTF-8 support often leads to mojibake (garbled text) when handling non-ASCII characters.
The core challenge lies in stripping the HTML markup without losing the semantic meaning that constitutes readability. A simple regex-based approach might seem tempting for its brevity, but it is rarely a viable solution for production environments. Regular expressions cannot reliably parse nested tags or handle escaping sequences correctly. Instead, you need to leverage PHP's built-in DOM parser or a specialized library designed to interpret HTML entities and tag attributes properly.
The Limitations of Simple Stripping
One might consider using strip_tags() immediately. This function removes all tags except those in the optional $allow_tags parameter. However, this is fundamentally insufficient for email. It ignores content inside <pre> or <code> blocks, fails to convert line breaks within paragraphs into actual newlines, and completely discards the structural hierarchy that determines font size or bolding (though these are often lost anyway in plain text).
More critically, strip_tags() does not decode HTML entities. If your TinyMCE content contains <br>, a naive strip will leave those entities intact, resulting in the literal text "br" instead of a line break. Similarly, UTF-8 characters encoded as entities (e.g., é) will remain encoded unless explicitly decoded.
A Robust Approach with DOMDocument
The most reliable method without relying on external dependencies is using PHP's DOMDocument combined with strip_tags. This approach allows you to first decode entities and then selectively clean the content while preserving whitespace where necessary.
Here is a practical implementation pattern:
function htmlToPlainText($html) {
// Create a DOM document
$dom = new DOMDocument();
// Prevent warnings from malformed HTML by loading with options
libxml_use_internal_errors(true);
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
libxml_clear_errors();
// Extract the body content if present
$body = $dom->getElementsByTagName('body')->item(0);
// Serialize the HTML back to a string
$outputHtml = $dom->saveHTML($body);
// Decode HTML entities and convert special characters
$outputText = html_entity_decode($outputHtml, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
// Replace common inline styles and tags that don't translate well
// Remove <style>, <script>, <link>, etc.
$outputText = preg_replace('#<[sS][cC][rR][iI][pP][tT]#', '', $outputText);
$outputText = preg_replace('#<[sS][tT][yY][lL][eE]#', '', $outputText);
// Convert <br> to newline, handling multiple occurrences
$outputText = preg_replace('#<br[\s>]*>#', "\n", $outputText);
// Handle paragraph tags by adding double newlines
$outputText = preg_replace('#</?[pP][\s>]*>#i', "\n\n", $outputText);
// Clean up extra whitespace and trim the result
return trim(preg_replace('/[^\S\r\n]+/', ' ', $outputText));
}
This method ensures that UTF-8 characters are handled correctly during the initial load. The regex replacements target specific tags that strip_tags would leave behind or misinterpret, ensuring the output is clean for email clients.
Leveraging Existing Libraries
If you require advanced formatting preservationâsuch as mapping <i> to underscores or <b> to bold text as seen in some legacy systemsâyou might look at dedicated libraries. The html2text class mentioned in community discussions provides this mapping capability, but its UTF-8 handling is a known weakness.
For modern PHP applications, particularly those built on frameworks like Laravel, it is often better to evaluate the trade-off between writing a custom utility and adopting a maintained package. If you choose a third-party library, ensure it explicitly supports UTF-8 input and provides configuration for entity decoding. Avoid relying on unverified forks of older tools unless they have been actively updated to address security vulnerabilities in parser handling.
Final Considerations for Email Clients
Remember that the goal is readability, not fidelity. Most email clients will strip HTML anyway when rendering plain text versions. Therefore, focus on normalizing line breaks and ensuring no encoding errors occur. If your application uses Laravel, you can encapsulate this logic within a service provider or a helper package to keep your controllers clean. Always test the output across major email clients (Gmail, Outlook, Apple Mail) before deploying, as their rendering engines handle newline characters differently.
