Converting HTML to plain text in PHP for e-mail
Convert HTML to plain text in PHP using the built-in function strip_tags()
. This function efficiently strips away HTML tags and produces a clean plain text outcome, perfect for emails.
Code snippet:
For preserving formatting like line breaks, replace <br>
tags with \n
before using strip_tags()
.
Keep the style with html2text
If you want to convert HTML but aren't ready to let go of all the formatting, then use the open-source html2text library. This maintains the soul of your HTML document while converting it to plain text.
Composer installation:
Code snippet:
Dealing with UTF-8 characters
Working with UTF-8 characters? Default PHP might kick up a fuss. Use mb_convert_encoding()
to calm things down before stripping tags.
Pro level: lynx solution
For extreme HTML enthusiasts, the lynx text browser combined with proc_open()
in PHP would provide high-end rendering of HTML into a human-readable format.
Lynx conversion example:
Tip: Verify lynx's output to circumvent security slip-ups because nobody wants an executable surprise in their mail!
A word about License and Contributions
When using html2text, beware of the Eclipse Public License. This license comes with its own dressing room and diet, so compatibility with other scripts and libraries may be an issue.
Contributing to open-source projects is like voting. It makes the tools better, and when everybody does it, everyone wins! So head to the html2text repository to contribute and #MakeHTMLGreatAgain.
Look up other libraries such as php-variable-sanitizer
and useful-php-scripts
for advanced sanitation and functionalities. Remember to read and understand the licensing terms before using them, especially for commercial use.
Was this article helpful?