Html2Text\Html2Text::convert PHP Method

convert() static public method

In particular, it tries to maintain the following features:

  • Links are maintained, with the 'href' copied over
  • Information in the <head> is lost
static public convert ( string $html ) : string
$html string the input HTML
return string the HTML converted, as best as possible, to text
    static function convert($html)
    {
        // replace &nbsp; with spaces
        $html = str_replace("&nbsp;", " ", $html);
        $html = str_replace(" ", " ", $html);
        if (static::isOfficeDocument($html)) {
            // remove office namespace
            $html = str_replace(array("<o:p>", "</o:p>"), "", $html);
        }
        $html = static::fixNewlines($html);
        if (mb_detect_encoding($html, "UTF-8", true)) {
            $html = mb_convert_encoding($html, "HTML-ENTITIES", "UTF-8");
        }
        $doc = new \DOMDocument();
        if (!$doc->loadHTML($html)) {
            throw new Html2TextException("Could not load HTML - badly formed?", $html);
        }
        if (static::isOfficeDocument($html)) {
            // remove office namespace
            $doc = static::fixMSEncoding($doc);
        }
        $output = static::iterateOverNode($doc);
        // remove leading and trailing spaces on each line
        $output = preg_replace("/[ \t]*\n[ \t]*/im", "\n", $output);
        $output = preg_replace("/ *\t */im", "\t", $output);
        // remove unnecessary empty lines
        $output = preg_replace("/\n\n\n*/im", "\n\n", $output);
        // remove leading and trailing whitespace
        $output = trim($output);
        return $output;
    }

Usage Example

コード例 #1
0
ファイル: DataMapperModel.php プロジェクト: hughnguy/php
 /**
  * Sends an email
  * @param \Swift_Message $message An email message
  * @param string $content The message body in HTML
  * @return int The number of recipients the message was delivered to
  */
 protected static function sendEmail(\Swift_Message $message, $content)
 {
     // Lazy mailer instantiation
     if (!self::$mailer) {
         self::$mailer = \Swift_Mailer::newInstance(\Swift_SmtpTransport::newInstance(SMTP_SERVER, SMTP_SERVER_PORT));
     }
     $message->setBody($content, 'text/html', 'utf-8');
     $message->addPart(\Html2Text\Html2Text::convert(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8')), 'text/plain', 'utf-8');
     return self::$mailer->send($message);
 }
All Usage Examples Of Html2Text\Html2Text::convert