soundasleep / html2text
一个将 HTML 转换为纯文本格式的 PHP 脚本
2.1.0
2023-01-06 09:28 UTC
Requires
- php: ^7.3|^8.0
- ext-dom: *
- ext-libxml: *
Requires (Dev)
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^7.0|^8.0|^9.0
README
html2text 是一个非常简单的脚本,使用 DOM 方法将 HTML 转换为类似浏览器渲染的格式 - 完美适用于需要快速文本表示的地方。例如
<html> <title>Ignored Title</title> <body> <h1>Hello, World!</h1> <p>This is some e-mail content. Even though it has whitespace and newlines, the e-mail converter will handle it correctly. <p>Even mismatched tags.</p> <div>A div</div> <div>Another div</div> <div>A div<div>within a div</div></div> <a href="http://foo.com">A link</a> </body> </html>
将被转换为
Hello, World!
This is some e-mail content. Even though it has whitespace and newlines, the e-mail converter will handle it correctly.
Even mismatched tags.
A div
Another div
A div
within a div
[A link](http://foo.com)
查看原始博客文章或相关的StackOverflow 答案。
安装
{
"require": {
"soundasleep/html2text": "~1.1"
}
}
然后可以非常简单地使用它
$text = \Soundasleep\Html2Text::convert($html);
您还可以包含提供的 html2text.php 并使用 $text = convert_html_to_text($html);。
选项
将选项作为第二个参数传递给 convert,例如
$options = array( 'ignore_errors' => true, // other options go here ); $text = \Soundasleep\Html2Text::convert($html, $options);
测试
在 tests/ 目录中提供了一些非常基本的测试。使用 composer install && vendor/bin/phpunit 运行它们。
故障排除
找不到类 'DOMDocument'
您需要为您的 PHP 版本 安装 PHP XML 扩展。例如 apt-get install php7.4-xml
许可
html2text 在 MIT 许可 下授权,使其适合 Eclipse 和 GPL 项目。
其他版本
还可以查看 html2text_ruby,Ruby 实现。