2026-07-15

Converting HTML to plain text in PHP for e-mail

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

Converting HTML to plain text in PHP for e-mail

The Developer's Guide: Robustly Converting HTML to Plain Text in PHP for Email

When dealing with dynamic content generated by rich text editors like TinyMCE, the next crucial step is preparing that content for delivery—especially when sending it via email. You need clean, readable plain text, free from distracting formatting, while preserving essential structure. The challenge, as you've encountered, lies in finding a method that is robust, handles complex nesting, and correctly manages character encoding, particularly UTF-8.

As senior developers, we know that relying on simple string manipulation or older, less maintained libraries often leads to subtle bugs when dealing with real-world, messy HTML. Let’s dive into the most reliable methods for tackling this conversion in PHP.

Why Simple Stripping Fails: The Need for Structure

Many initial attempts at HTML-to-text conversion involve using regular expressions or simple str_replace() calls to remove tags (e.g., <p>, <b>, <i>). While this works for very basic content, it breaks down quickly when dealing with nested structures, attributes, or multi-line formatting that might be necessary for proper email readability.

For instance, if you have complex formatting, simple replacement often introduces unwanted spaces or incorrectly merges text segments, especially when handling non-ASCII characters inherent in UTF-8. This lack of structural awareness means the resulting plain text is often structurally inaccurate for the recipient.

The Professional Approach: Leveraging DOMDocument

The most robust and developer-friendly way to parse HTML in PHP is by utilizing the native DOMDocument class, which allows you to treat the HTML as a structured tree rather than just a string of characters. This method gives us precise control over what we extract, making it far superior for complex tasks like content extraction.

Here is how you can use DOMDocument to strip HTML tags and extract the visible text:

<?php

$html = '<p>This is <b>important</b> text with some <i>italic</i> formatting.</p>';

// 1. Load the HTML into a DOMDocument object
$dom = new DOMDocument();
// Suppress warnings about malformed HTML if necessary
@$dom->loadHTML($html);

// 2. Get all body elements
$elements = $dom->getElementsByTagName('body');

$plainText = '';

if ($elements->length > 0) {
    foreach ($elements as $body) {
        // Iterate through all child nodes (like paragraphs, spans, etc.)
        $text = '';
        $body->childNodes->forEach(function($node) use (&$text) {
            // Only concatenate text nodes, skipping elements themselves
            if ($node->nodeType === XML_TEXT_NODE) {
                $text .= $node->nodeValue;
            }
        });
        $plainText .= $text . "\n\n"; // Add separation for readability
    }
}

echo $plainText;

?>

Best Practices for Encoding and Frameworks

When working with modern applications, especially those built on robust frameworks like Laravel, ensuring correct character encoding is non-negotiable. Since your content originated from TinyMCE, it is almost certainly UTF-8 encoded. By using DOMDocument, PHP correctly handles the internal structure of the document, minimizing the risk of encoding errors that plague simpler string methods.

Furthermore, when architecting backend logic for data manipulation—whether it’s processing user input or preparing output for services like email delivery—it is vital to rely on well-tested tools and native capabilities rather than bespoke solutions. This principle applies across the board; building reliable systems requires a solid foundation, much like ensuring the stability of an application built with modern PHP principles found in projects like those supported by laravelcompany.com.

Conclusion: Choosing Your Tool

While third-party libraries exist, for core HTML parsing tasks within a standard PHP environment, mastering DOMDocument provides maximum control and avoids dependency management headaches. It allows you to write code that is self-documenting and handles the complexities of HTML structure correctly, ensuring your plain text output is clean, accurate, and perfectly formatted for any email client. For robust, scalable solutions, native tools often prove to be the most powerful starting point.

Note: Blog content is currently available in English.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.