如何在支援 UTF-8 的 PHP 中將 HTML 轉換為純文字以發送電子郵件?

Linda Hamilton
發布: 2024-11-13 10:50:02
原創
756 人瀏覽過

How to Convert HTML to Plain Text for Emails in PHP with UTF-8 Support?

Converting HTML to Plain Text for Emails in PHP

Often, we need to convert HTML content, such as the text generated by TinyMCE, into plain text for use in emails. While there are various solutions, finding one with robust UTF-8 support and flexible formatting options can be challenging.

Recommended Solution: html2text

Considering the need for UTF-8 support and customizable formatting, html2text stands out as a recommended solution. Licensed under the Eclipse Public License, html2text utilizes PHP's DOM methods to convert HTML to plain text. It effectively traverses the resulting DOM, extracting plain text while maintaining the desired formatting.

Usage

Installing html2text via Composer is straightforward:

// Composer (if installed)
$text = Html2Text\Html2Text::convert($html);
登入後複製

Alternatively, if you prefer the individual file approach, follow these steps:

  1. Include the html2text.php file:

    require('html2text.php');
    登入後複製
  2. Call the convert_html_to_text() function:

    $text = convert_html_to_text($html);
    登入後複製

Benefits of html2text

  • Comprehensive UTF-8 support
  • Customizable formatting options, such as mapping HTML tags to plain text formatting
  • Open source and contributions are encouraged

Alternatives to Consider

While html2text is a solid choice, here are a few other options worth considering:

  • [PHP's strip_tags() function](https://www.php.net/manual/en/function.strip-tags.php): Removes HTML tags from a string, leaving only the plain text.
  • [GeekGap's HTML Purifier](https://htmlpurifier.org/): An extensive HTML filtering library that can clean and strip tags.

Important Considerations

  • Note that html2text is distributed under the Eclipse Public License, unlike html2text.php, which was previously licensed under the GPL.
  • LKessler's link attribution may not be compatible with all open source licenses.

以上是如何在支援 UTF-8 的 PHP 中將 HTML 轉換為純文字以發送電子郵件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板