복붙노트

전자 메일 용 PHP에서 HTML을 일반 텍스트로 변환

PHP

전자 메일 용 PHP에서 HTML을 일반 텍스트로 변환

TinyMCE를 사용하여 내 사이트의 텍스트 서식을 최소화합니다. 제작 된 HTML에서 전자 메일 용 일반 텍스트로 변환하고 싶습니다. html2text라는 클래스를 사용했지만 실제로 UTF-8 지원이 부족합니다. 그러나 특정 HTML 태그를 일반 텍스트 서식으로 매핑하는 것처럼 HTML에서 태그를 사용하는 텍스트 주위에 밑줄을 넣는 것과 같습니다.

누구든지 PHP에서 HTML을 일반 텍스트로 변환하는 비슷한 접근법을 사용합니까? 만약 그렇다면 : 제가 사용할 수있는 타사 수업을 권합니까? 또는이 문제를 어떻게 해결할 수 있습니까?

해결법

  1. ==============================

    1.Eclipse Public License에 따라 라이센스가 부여 된 html2text (예제 HTML - 텍스트)를 사용하십시오. PHP의 DOM 메소드를 사용하여 HTML에서로드 한 다음 결과 DOM을 반복하여 일반 텍스트를 추출합니다. 용법:

    Eclipse Public License에 따라 라이센스가 부여 된 html2text (예제 HTML - 텍스트)를 사용하십시오. 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);
    

    불완전하지만 오픈 소스이며 기여도 환영합니다.

    다른 전환 스크립트 관련 문제 :

  2. ==============================

    2.믿을만한 strip_tags 함수가 있습니다. 그것은 꽤 아니지만. 그것은 단지 위생적입니다. 당신은 멋진 밑줄을 얻기 위해 그것을 대체 할 문자열과 결합 할 수 있습니다.

    믿을만한 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)));
    
    ?>
    
  3. ==============================

    3.DOMDocument를 사용하여 HTML에서 텍스트로 변환하는 것은 실행 가능한 솔루션입니다. PHP5가 필요한 HTML2Text를 고려하십시오.

    DOMDocument를 사용하여 HTML에서 텍스트로 변환하는 것은 실행 가능한 솔루션입니다. PHP5가 필요한 HTML2Text를 고려하십시오.

    UTF-8과 관련하여 "howto"페이지에 다음과 같이 적혀 있습니다.

    저자는이 문제를 해결하기위한 몇 가지 접근법을 제공하며 HTML2Text 버전 2 (DOMDocument 사용)는 UTF-8을 지원한다고 명시합니다.

    상업적 사용에 대한 제한 사항에 유의하십시오.

  4. ==============================

    4.여기에 또 다른 해결책이 있습니다.

    여기에 또 다른 해결책이 있습니다.

    $cleaner_input = strip_tags($text);
    

    sanitization 함수의 다른 변형은 다음을 참조하십시오.

    https://RunForgithub.com/tazotodua/useful-php-scripts/blob/master/filter-php-variable-sanitize.php

  5. ==============================

    5.lynx를 -stdin과 -dump 옵션과 함께 사용하면 다음과 같은 결과를 얻을 수 있습니다 :

    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";
    }
    
  6. ==============================

    6.이 함수를 테스트 할 수 있습니다.

    이 함수를 테스트 할 수 있습니다.

    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);
    }
    
  7. ==============================

    7.필자는 기존의 솔루션 중 간단한 HTML 전자 메일을 단순한 일반 텍스트 파일로 찾지 못했습니다.

    필자는 기존의 솔루션 중 간단한 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
    
  8. ==============================

    8.Markdownify는 HTML을이 사이트에서 사용되는 일반 텍스트 서식 시스템 인 Markdown으로 변환합니다.

    Markdownify는 HTML을이 사이트에서 사용되는 일반 텍스트 서식 시스템 인 Markdown으로 변환합니다.

  9. ==============================

    9.Markdownify 나를 위해 훌륭하게 일했습니다! 무엇에 대해 언급해야한다 : 완벽하게 utf-8을 지원한다. 왜 내가 html2text (이 글의 앞 부분에서 언급했는지)보다 다른 해결책을 찾고있는 가장 큰 이유는 무엇인가.

    Markdownify 나를 위해 훌륭하게 일했습니다! 무엇에 대해 언급해야한다 : 완벽하게 utf-8을 지원한다. 왜 내가 html2text (이 글의 앞 부분에서 언급했는지)보다 다른 해결책을 찾고있는 가장 큰 이유는 무엇인가.

  10. ==============================

    10.나는 OP와 같은 문제를 둘러 보았고, 위의 대답에서 몇 가지 해결책을 시도해도 내 시나리오에서는 효과가 없었습니다. 결국 왜 볼 수 있습니다.

    나는 OP와 같은 문제를 둘러 보았고, 위의 대답에서 몇 가지 해결책을 시도해도 내 시나리오에서는 효과가 없었습니다. 결국 왜 볼 수 있습니다.

    대신이 유용한 스크립트를 발견하여 혼란을 피하기 위해 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가 다른 것보다 나은 이유는 무엇입니까?

  11. ==============================

    11.나는 방금 PHP 함수 "strip_tags ()"를 찾았으며 나의 경우에는 작동한다.

    나는 방금 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?
    
  12. ==============================

    12.태그를 완전히 제거하고 태그 안에 내용을 유지하고 싶지 않으면 DOMDocument를 사용하고 다음과 같이 루트 노드의 textContent를 추출 할 수 있습니다.

    태그를 완전히 제거하고 태그 안에 내용을 유지하고 싶지 않으면 DOMDocument를 사용하고 다음과 같이 루트 노드의 textContent를 추출 할 수 있습니다.

    function html2text($html) {
        $dom = new DOMDocument();
        $dom->loadHTML("<body>" . strip_tags($html, '<b><a><i><div><span><p>') . "</body>");
        $xpath = new DOMXPath($dom);
        $node = $xpath->query('body')->item(0);
        return $node->textContent; // text
    }
    
    $p = 'this is <b>test</b>. <p>how are <i>you?</i>. <a href="#">I\'m fine!</a></p>';
    print html2text($p);
    // this is test. how are you?. I'm fine!
    

    이 접근법의 한 가지 장점은 외부 패키지가 필요 없다는 것입니다.

  13. ==============================

    13.HTML 특수 문자를 변환하고 그냥 제거하지 않고 일반 텍스트를 준비하는 경우이 방법이 저에게 효과가있는 해결책이었습니다 ...

    HTML 특수 문자를 변환하고 그냥 제거하지 않고 일반 텍스트를 준비하는 경우이 방법이 저에게 효과가있는 해결책이었습니다 ...

    function htmlToPlainText($str){
        $str = str_replace('&nbsp;', ' ', $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 (&nbsp;) a test</p>
    <div>Yes this is! &amp; does it get "processed"? </div>'
    
    htmlToPlainText($string);
    // "this is ( ) a test. Yes this is! & does it get processed?"`
    

    ENT_QUOTES가있는 html_entity_decode | ENT_XML1은 ' htmlspecialchars_decode는 & amp; html_entity_decode는 '& lt; strip_tags는 남아있는 모든 HTML 태그를 제거합니다.

  14. ==============================

    14.

    public function plainText($text)
    {
        $text = strip_tags($text, '<br><p><li>');
        $text = preg_replace ('/<[^>]*>/', PHP_EOL, $text);
    
        return $text;
    }
    

    $ string = "문자열 1"문자열 2 <문자열> <문자열> 3 ;

    echo planText ($ text);

    산출 문자열 1 문자열 2 문자열 3 문자열 4 문자열 5

  15. from https://stackoverflow.com/questions/1884550/converting-html-to-plain-text-in-php-for-e-mail by cc-by-sa and MIT license