CakePHP从纯文本电子邮件中删除HTML

时间:2012-11-30 09:31:56

标签: php cakephp

我在我的cakephp应用程序(2.2)中使用电子邮件组件,在我的应用程序中添加新文章时向订阅的人发送电子邮件。

我使用TinyMCE允许管理员用户格式化文本,这会导致某些格式化HTML保存在数据库中(这很好)但是我想通过电子邮件格式向选择的用户发送电子邮件格式的文章,包括html和纯文本何时添加新文章。这适用于html版本,但如何在保持html版本的同时从纯文本版本中删除html?到目前为止,我的代码是:

public function admin_add() {
    if ($this->request->is('post')) {
        $this->NewsArticle->create();
        if ($this->NewsArticle->save($this->request->data)) {

            // If is a tech alart - send email
            if ($this->request->data['NewsCategory']['NewsCategory']['0'] == '2') {

                // Email users who have opted in to webform updates
                $usersToEmail = $this->NewsArticle->query("SELECT username, tech_email FROM users WHERE tech_email = 1");

                // Loop throughh all opt'ed in users
                foreach ($usersToEmail as $user) {

                    $this->Email->template = 'newTechAlert';
                    $this->Email->from    = 'Client Area <clientarea@someurl.co.uk>';
                    $this->Email->to      = $user['users']['username'];
                    $this->Email->subject = 'New Technical Alert';
                    // Send as both HTML and Text
                                            $this->Email->sendAs = 'both';

                    // Set vars for email
                    $this->set('techAlertTitle', $this->request->data['NewsArticle']['title']);

                    ##  NEED TO STRIP THE HTML OUT FOR NONE HTML EMAILS HERE - BUT HOW???
                    $this->set('techAlertBody', $this->request->data['NewsArticle']['body']);


                    $this->set('user', $user['users']['username']);
                    $this->Email->send();

                }

            }

2 个答案:

答案 0 :(得分:4)

我用:

$this->Email->emailFormat('both');

// Convert <br> to \n
$text = preg_replace('/<br(\s+)?\/?>/i', "\n", $html);
// Remove html markup
$text = trim(strip_tags($text));
// Replace multiple (one ore more) line breaks with a single one.
$text = preg_replace("/(\r\n|\r|\n)+/", "\n", $text);

$this->Email->viewVars(compact('text', 'html'));

请注意,如果您预先安排,则应在每次运行后重置电子邮件类以避免出现问题:

$this->Email->reset();

答案 1 :(得分:2)

您可以使用php strip_tags方法 http://php.net/manual/en/function.strip-tags.php

//HTML VERSION
$this->set('techAlertHtmlBody', $this->request->data['NewsArticle']['body']);

//PLAIN TEXT VERSION
$this->set('techAlertPlainBody', strip_tags($this->request->data['NewsArticle']['body']));

您还可以将第二个参数传递给该函数,以便仍然允许换行符或href标记。