86

TinyMCEを使用して、サイト内のテキストの書式設定を最小限に抑えています。生成された HTML から、電子メール用のプレーン テキストに変換したいと考えています。私はhtml2textというクラスを使用してきましたが、特に UTF-8 サポートが不足しています。ただし、特定の HTML タグをプレーン テキスト形式にマップする点は気に入っています。たとえば、以前 HTML に <i> タグが含まれていたテキストをアンダースコアで囲みます。

PHPでHTMLをプレーンテキストに変換するために同様のアプローチを使用する人はいますか? もしそうなら、私が使用できるサードパーティのクラスをお勧めしますか? または、この問題にどのように取り組むのが最善ですか?

4

14 に答える 14

107

Eclipse Public Licenseの下でライセンス供与されているhtml2text ( HTML to textの例) を使用します。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);

不完全ではありますが、オープン ソースであり、貢献を歓迎します。

他の変換スクリプトの問題:

  • html2text (GPL) は EPL 互換ではないためです。
  • lkessler のリンク(帰属) は、ほとんどのオープン ソース ライセンスと互換性がありません。
于 2010-04-02T00:32:39.087 に答える
14

DOMDocumentを使用して HTML からテキストに変換することは、実行可能なソリューションです。PHP5 を必要とする HTML2Text を考えてみます。

UTF-8 に関しては、「ハウツー」ページに次のように書かれています。

PHP 自体の Unicode サポートは非​​常に貧弱で、常に utf-8 を正しく処理するとは限りません。html2text スクリプトは (mbstring モジュールを必要とせずに) Unicode 対応のメソッドを使用していますが、PHP 独自のエンコーディング処理に常に対応できるとは限りません。PHP は Unicode や utf-8 のようなエンコーディングを実際には理解せず、ISO-8859 ファミリーの 1 つである傾向があるシステムのベース エンコーディングを使用します。その結果、テキスト エディターで有効な文字のように見えるもの (utf-8 またはシングルバイトのいずれか) が、PHP によって誤って解釈される可能性があります。したがって、有効な文字を html2text に入力していると思っていても、そうではない可能性があります。

著者は、これを解決するためのいくつかのアプローチを提供し、HTML2Text のバージョン 2 (DOMDocument を使用) が UTF-8 をサポートしていると述べています。

商用利用の制限に注意してください。

于 2010-03-17T21:52:00.420 に答える
13

信頼できる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)));

?>
于 2009-12-10T23:07:44.503 に答える
9

-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";
}
于 2012-03-08T02:32:04.660 に答える
8

この機能をテストできます

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);
}
于 2013-12-13T03:40:18.467 に答える
6

単純な HTML メールから単純なプレーン テキスト ファイルまで、既存のソリューションに適合するものは見つかりませんでした。

このリポジトリを開きました。誰かの役に立てば幸いです。ちなみに、MITライセンス:)

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
于 2016-11-21T15:34:28.547 に答える
3

Markdownifyは HTML を Markdown に変換します。Markdown は、まさにこのサイトで使用されているプレーンテキスト形式のシステムです。

于 2011-12-28T10:14:19.470 に答える
1

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?
于 2012-05-16T21:17:33.780 に答える