将 HTML 转换为 PHP 中的纯文本以用于电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1884550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting HTML to plain text in PHP for e-mail
提问by Justin Stayton
I use TinyMCEto allow minimal formatting of text within my site. From the HTML that's produced, I'd like to convert it to plain text for e-mail. I've been using a class called html2text, but it's really lacking in UTF-8 support, among other things. I do, however, like that it maps certain HTML tags to plain text formatting — like putting underscores around text that previously had <i> tags in the HTML.
我使用TinyMCE来允许在我的站点中最小化文本格式。从生成的 HTML 中,我想将其转换为电子邮件的纯文本。我一直在使用一个名为html2text的类,但它确实缺乏对 UTF-8 的支持,等等。然而,我喜欢它将某些 HTML 标签映射到纯文本格式——比如在 HTML 中以前有 <i> 标签的文本周围放置下划线。
Does anyone use a similar approach to converting HTML to plain text in PHP? And if so: Do you recommend any third-party classes that I can use? Or how do you best tackle this issue?
有没有人使用类似的方法在 PHP 中将 HTML 转换为纯文本?如果是这样:您是否推荐我可以使用的任何第三方类?或者你如何最好地解决这个问题?
回答by jevon
Use html2text(example HTMLto text), licensed under the Eclipse Public License. It uses PHP's DOM methods to load from HTML, and then iterates over the resulting DOM to extract plain text. Usage:
使用html2text(示例HTML到文本),在Eclipse Public License下获得许可。它使用 PHP 的 DOM 方法从 HTML 加载,然后迭代生成的 DOM 以提取纯文本。用法:
// when installed using the Composer package
$text = Html2Text\Html2Text::convert($html);
// usage when installed using html2text.php
require('html2text.php');
$text = convert_html_to_text($html);
Although incomplete, it is open source and contributions are welcome.
虽然不完整,但它是开源的,欢迎贡献。
Issues with other conversion scripts:
其他转换脚本的问题:
- Since html2text(GPL) is not EPL-compatible.
- lkessler's link(attribution) is incompatible with most open source licenses.
- 由于html2text(GPL) 与 EPL 不兼容。
- lkessler 的链接(署名)与大多数开源许可证不兼容。
回答by T.Todua
here is another solution:
这是另一种解决方案:
$cleaner_input = strip_tags($text);
For other variations of sanitization functions, see:
有关消毒功能的其他变体,请参阅:
https://github.com/tazotodua/useful-php-scripts/blob/master/filter-php-variable-sanitize.php
https://github.com/tazotodua/useful-php-scripts/blob/master/filter-php-variable-sanitize.php
回答by lkessler
Converting from HTML to text using a DOMDocumentis a viable solution. Consider HTML2Text, which requires PHP5:
使用DOMDocument从 HTML 转换为文本是一个可行的解决方案。考虑 HTML2Text,它需要 PHP5:
- http://www.howtocreate.co.uk/php/html2texthowto.html
- http://www.howtocreate.co.uk/php/
- http://www.howtocreate.co.uk/jslibs/termsOfUse.html
- http://www.howtocreate.co.uk/php/html2texthowto.html
- http://www.howtocreate.co.uk/php/
- http://www.howtocreate.co.uk/jslibs/termsOfUse.html
Regarding UTF-8, the write-up on the "howto" page states:
关于 UTF-8,“howto”页面上的文章指出:
PHP's own support for unicode is quite poor, and it does not always handle utf-8 correctly. Although the html2text script uses unicode-safe methods (without needing the mbstring module), it cannot always cope with PHP's own handling of encodings. PHP does not really understand unicode or encodings like utf-8, and uses the base encoding of the system, which tends to be one of the ISO-8859 family. As a result, what may look to you like a valid character in your text editor, in either utf-8 or single-byte, may well be misinterpreted by PHP. So even though you think you are feeding a valid character into html2text, you may well not be.
PHP 自己对 unicode 的支持很差,而且它并不总是正确处理 utf-8。尽管 html2text 脚本使用 unicode-safe 方法(不需要 mbstring 模块),但它不能总是处理 PHP 自己的编码处理。PHP 并不真正理解 unicode 或 utf-8 之类的编码,而是使用系统的基本编码,这往往是 ISO-8859 系列之一。因此,在您的文本编辑器中看起来像是有效字符的 utf-8 或单字节字符很可能会被 PHP 误解。因此,即使您认为将有效字符输入到 html2text 中,也可能不是。
The author provides several approaches to solving this and states that version 2 of HTML2Text (using DOMDocument) has UTF-8 support.
作者提供了几种解决此问题的方法,并指出 HTML2Text 的第 2 版(使用 DOMDocument)支持 UTF-8。
Note the restrictions for commercial use.
请注意商业用途的限制。
回答by pestilence669
There's the trusty strip_tagsfunction. It's not pretty though. It'll only sanitize. You could combine it with a string replace to get your fancy underscores.
有值得信赖的strip_tags函数。不过也不是很漂亮。它只会消毒。您可以将它与字符串替换结合使用以获得您喜欢的下划线。
<?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)));
?>
回答by nad2000
You can use lynx with -stdin and -dump options to achieve that:
您可以使用带有 -stdin 和 -dump 选项的 lynx 来实现:
<?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";
}
回答by HoangLong85
You can test this 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);
}
回答by Rob
I didn't find any of the existing solutions fitting - simple HTML emails to simple plain text files.
我没有找到任何适合的现有解决方案 - 简单的 HTML 电子邮件到简单的纯文本文件。
I've opened up this repository, hope it helps someone. MIT license, by the way :)
我已经打开了这个存储库,希望它可以帮助某人。麻省理工学院许可证,顺便说一句:)
https://github.com/RobQuistNL/SimpleHtmlToText
https://github.com/RobQuistNL/SimpleHtmlToText
Example:
例子:
$myHtml = '<b>This is HTML</b><h1>Header</h1><br/><br/>Newlines';
echo (new Parser())->parseString($myHtml);
returns:
返回:
**This is HTML**
### Header ###
Newlines
回答by Jay
If you want to convertthe HTML special characters and not just remove them as well as strip things down and prepare for plain text this was the solution that worked for me...
如果您想转换HTML 特殊字符,而不仅仅是删除它们以及剥离内容并准备纯文本,那么这就是对我有用的解决方案......
function htmlToPlainText($str){
$str = str_replace(' ', ' ', $str);
$str = html_entity_decode($str, ENT_QUOTES | ENT_COMPAT , 'UTF-8');
$str = html_entity_decode($str, ENT_HTML5, 'UTF-8');
$str = html_entity_decode($str);
$str = htmlspecialchars_decode($str);
$str = strip_tags($str);
return $str;
}
$string = '<p>this is ( ) a test</p>
<div>Yes this is! & does it get "processed"? </div>'
htmlToPlainText($string);
// "this is ( ) a test. Yes this is! & does it get processed?"`
html_entity_decode w/ ENT_QUOTES | ENT_XML1 converts things like 'htmlspecialchars_decode converts things like &html_entity_decode converts things like '<and strip_tags removes any HTML tags left over.
html_entity_decode w/ENT_QUOTES | ENT_XML1 转换像'htmlspecialchars_decode 这样的东西转换像 html_entity_decode 这样的&东西'<,strip_tags 移除任何剩下的 HTML 标签。
回答by outis
Markdownifyconverts HTML to Markdown, a plain-text formatting system used on this very site.
Markdownify将 HTML 转换为 Markdown,这是本网站上使用的纯文本格式系统。
回答by Chris Dev
I came around the same problem as the OP, and trying some solutions from the top answers above didn't prove to work for my scenarios. See why at the end.
我遇到了与 OP 相同的问题,并且从上面的最佳答案中尝试了一些解决方案并没有证明对我的场景有效。最后看看为什么。
Instead, I found this helpful script, to avoid confusion let's call it html2text_roundcube, available under GPL:
相反,我发现了这个有用的脚本,为了避免混淆,我们称之为html2text_roundcube,在 GPL 下可用:
It's actually an updated version of an already mentioned script - http://www.chuggnutt.com/html2text.php- updated by RoundCube mail.
它实际上是已经提到的脚本的更新版本http://www.chuggnutt.com/html2text.php——由 RoundCube 邮件更新。
Usage:
用法:
$h2t = new \Html2Text\Html2Text('Hello, "<b>world</b>"');
echo $h2t->getText(); // prints Hello, "WORLD"
Why html2text_roundcubeproved better than the others:
为什么html2text_roundcube证明比其他人更好:
Script
http://www.chuggnutt.com/html2text.phpdidn't work out of the box for cases with special HTML codes/names (egä), or unpaired quotes (eg<p>25" Monitor</p>).Script
https://github.com/soundasleep/html2texthad no option to hide or group the links at the end of the text, making a usual HTML page look bloated with links when in text-plain format; customizing the code for special treatment of how the transformation is done is not as straight forward as simply editing an array inhtml2text_roundcube.
http://www.chuggnutt.com/html2text.php对于具有特殊 HTML 代码/名称(例如ä)或不成对引号(例如<p>25" Monitor</p>)的情况,脚本无法开箱即用。脚本
https://github.com/soundasleep/html2text无法隐藏或分组文本末尾的链接,使得普通的 HTML 页面在纯文本格式时看起来因链接而臃肿;自定义代码以对如何完成转换进行特殊处理并不像简单地在html2text_roundcube.

