在PHP中将HTML转换为纯文本以用于电子邮件

我使用TinyMCE来允许我的网站中的文本格式最小化。 从生成的HTML,我想将其转换为纯文本的电子邮件。 我一直在使用一个名为html2text的类,但是在UTF-8支持方面真的很缺乏。 不过,我确实喜欢将某些HTML标记映射为纯文本格式,比如将以前在HTML中包含<i>标记的文本加上下划线。

有没有人使用类似的方法将HTML转换为纯文本的PHP? 如果是这样:你推荐任何我可以使用的第三方类吗? 或者你如何最好地解决这个问题?

使用Eclipse公共许可证下的html2text (示例HTML 文本 )。 它使用PHP的DOM方法从HTML加载,然后遍历生成的DOM来提取纯文本。 用法:

$text = convert_html_to_text($html); 

虽然不完整,但它是开源的,贡献是值得欢迎的。

其他转换脚本的问题:

  • 由于html2text (GPL)不是EPL兼容的。
  • lkessler的链接 (归属)与大多数开源许可证不兼容。

使用DOMDocument从HTML转换为文本是一个可行的解决scheme。 考虑HTML2Text,它需要PHP5:

关于UTF-8,“howto”页面上的说明写道:

PHP自己对unicode的支持很差,并不总是正确处理utf-8。 尽pipehtml2text脚本使用了unicode安全的方法(不需要mbstring模块),但它不能总是处理PHP自己的编码处理。 PHP并不真正理解Unicode或UTF-8等编码,并使用系统的基本编码,这往往是ISO-8859系列之一。 因此,在文本编辑器中看起来像是一个有效的字符,无论是utf-8还是单字节,都可能被PHP误解。 所以,即使你认为你正在给html2text一个有效的字符,你可能不会。

作者提供了几种方法来解决这个问题,并指出版本2的HTML2Text(使用DOMDocument)有UTF-8的支持。

请注意商业用途的限制。

有可靠的strip_tagsfunction。 虽然不是很漂亮 它只会消毒。 你可以把它与一个stringreplace来获得你的花式下划线。

 <?php // to strip all tags and wrap italics with underscore strip_tags(str_replace(array("<i>", "</i>"), array("_", "_"), $text)); // to preserve anchors... str_replace("|a", "<a", strip_tags(str_replace("<a", "|a", $text))); ?> 

您可以使用lynx和-stdin和-dump选项来实现:

 <?php $descriptorspec = array( 0 => array("pipe", "r"), // stdin is a pipe that the child will read from 1 => array("pipe", "w"), // stdout is a pipe that the child will write to 2 => array("file", "/tmp/htmp2txt.log", "a") // stderr is a file to write to ); $process = proc_open('lynx -stdin -dump 2>&1', $descriptorspec, $pipes, '/tmp', NULL); if (is_resource($process)) { // $pipes now looks like this: // 0 => writeable handle connected to child stdin // 1 => readable handle connected to child stdout // Any error output will be appended to htmp2txt.log $stdin = $pipes[0]; fwrite($stdin, <<<'EOT' <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>TEST</title> </head> <body> <h1><span>Lorem Ipsum</span></h1> <h4>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</h4> <h5>"There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..."</h5> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque et sapien ut erat porttitor suscipit id nec dui. Nam rhoncus mauris ac dui tristique bibendum. Aliquam molestie placerat gravida. Duis vitae tortor gravida libero semper cursus eu ut tortor. Nunc id orci orci. Suspendisse potenti. Phasellus vehicula leo sed erat rutrum sed blandit purus convallis. </p> <p> Aliquam feugiat, neque a tempus rhoncus, neque dolor vulputate eros, non pellentesque elit lacus ut nunc. Pellentesque vel purus libero, ultrices condimentum lorem. Nam dictum faucibus mollis. Praesent adipiscing nunc sed dui ultricies molestie. Quisque facilisis purus quis felis molestie ut accumsan felis ultricies. Curabitur euismod est id est pretium accumsan. Praesent a mi in dolor feugiat vehicula quis at elit. Mauris lacus mauris, laoreet non molestie nec, adipiscing a nulla. Nullam rutrum, libero id pellentesque tempus, erat nibh ornare dolor, id accumsan est risus at leo. In convallis felis at eros condimentum adipiscing aliquam nisi faucibus. Integer arcu ligula, porttitor in fermentum vitae, lacinia nec dui. </p> </body> </html> EOT ); fclose($stdin); echo stream_get_contents($pipes[1]); fclose($pipes[1]); // It is important that you close any pipes before calling // proc_close in order to avoid a deadlock $return_value = proc_close($process); echo "command returned $return_value\n"; } 

你可以testing这个function

 function html2text($Document) { $Rules = array ('@<script[^>]*?>.*?</script>@si', '@<[\/\!]*?[^<>]*?>@si', '@([\r\n])[\s]+@', '@&(quot|#34);@i', '@&(amp|#38);@i', '@&(lt|#60);@i', '@&(gt|#62);@i', '@&(nbsp|#160);@i', '@&(iexcl|#161);@i', '@&(cent|#162);@i', '@&(pound|#163);@i', '@&(copy|#169);@i', '@&(reg|#174);@i', '@&#(d+);@e' ); $Replace = array ('', '', '', '', '&', '<', '>', ' ', chr(161), chr(162), chr(163), chr(169), chr(174), 'chr()' ); return preg_replace($Rules, $Replace, $Document); } 

这是另一个解决scheme:

 $cleaner_input = strip_tags($text); 

我没有find任何现有的解决scheme – 简单的HTML电子邮件简单的纯文本文件。

我已经打开这个库,希望它可以帮助别人。 麻省理工学院的许可,顺便:)

https://github.com/RobQuistNL/SimpleHtmlToText

例:

 $myHtml = '<b>This is HTML</b><h1>Header</h1><br/><br/>Newlines'; echo (new Parser())->parseString($myHtml); 

收益:

 **This is HTML** ### Header ### Newlines 

Markdownify将HTML转换为Markdown,这是一个在这个网站上使用的纯文本格式系统。

Markdownify对我来说非常棒! 有什么必须提及它:它完全支持utf-8,为什么我正在寻找另一种解决scheme而不是html2text(本文前面提到的)的主要原因是什么。

我遇到了与OP相同的问题,并尝试从上面的答案上面的一些解决scheme没有certificate适用于我的scheme。 看看为什么在最后。

相反,我find了这个有用的脚本,为了避免混淆,我们把它html2text_roundcube ,在GPL下可用:

这实际上是一个已经提到的脚本的更新版本 – http://www.chuggnutt.com/html2text.php – 由RoundCube邮件更新。

用法:

 $h2t = new \Html2Text\Html2Text('Hello, &quot;<b>world</b>&quot;'); echo $h2t->getText(); // prints Hello, "WORLD" 

为什么html2text_roundcube比其他人更好:

  • 脚本http://www.chuggnutt.com/html2text.php不适用于带有特殊HTML代码/名称(例如&auml; )或不成对引号(例如<p>25" Monitor</p> )。

  • 脚本https://github.com/soundasleep/html2text没有select隐藏或分组链接在文本的末尾,使得通常的HTML页面看起来与文本格式的链接时臃肿; 自定义特殊处理代码的方式并不像直接在html2text_roundcube编辑数组那么简单。

我刚刚find了一个PHP函数“strip_tags()”,并在我的情况下工作。

我试图转换下面的HTML:

 <p><span style="font-family: 'Verdana','sans-serif'; color: black; font-size: 7.5pt;">&nbsp;</span>Many practitioners are optimistic that the eyeglass and contact lens industry will recover from the recent economic storm. Did your practice feel its affects?&nbsp; Statistics show revenue notably declined in 2008 and 2009. But interestingly enough, those that monitor these trends state that despite the industry's lackluster performance during this time, revenue has grown at an average annual rate&nbsp;of 2.2% over the last five years, to $9.0 billion in 2010.&nbsp; So despite the downturn, how were we able to manage growth as an industry?</p> 

应用strip_tags()函数后,我得到了以下输出:

 &amp;nbsp;Many practitioners are optimistic that the eyeglass and contact lens industry will recover from the recent economic storm. Did your practice feel its affects?&amp;nbsp; Statistics show revenue notably declined in 2008 and 2009. But interestingly enough, those that monitor these trends state that despite the industry&#039;s lackluster performance during this time, revenue has grown at an average annual rate&amp;nbsp;of 2.2% over the last five years, to $9.0 billion in 2010.&amp;nbsp; So despite the downturn, how were we able to manage growth as an industry? 
 public function planText($text) { $text = strip_tags($text, '<br><p><li>'); $text = preg_replace ('/<[^>]*>/', PHP_EOL, $text); return $text; } 

$text = "string 1<br>string 2<br/><ul><li>string 3</li><li>string 4</li></ul><p>string 5</p>";

echo planText($text);

产量
string1
string2
string3
string4
string5