【问题标题】:How to parse HTML content and add inline CSS如何解析 HTML 内容并添加内联 CSS
【发布时间】:2013-06-23 07:25:44
【问题描述】:

我有一个 HTML 编辑器,管理员可以在其中输入 HTML 电子邮件的内容,但为了在浏览器/客户端之间保持一致的样式,这需要包含内联 css。例如对于一个段落:

转换:

<p class="standard">

进入:

<p class="standard" style="-ms-text-size-adjust:100%; mso-line-height-rule:exactly; font-family:Helvetica, Arial, sans-serif; font-size:12px; line-height:18px; color:<?php echo $body_font_color; ?>; margin-top:0px; margin-bottom:0px;">

我认为这与流行的 Mail Chimp 作品相同,如果它们不存在,则添加内联样式。

段落只是示例,我还有表格和其他类可以添加样式。

【问题讨论】:

标签: php


【解决方案1】:

将文档加载到 PHP DOMDocument 对象中。然后,您将拥有遍历 DOM 树并进行所需更改的所有方法。

例如:

$doc = DOMDocument::loadHTML($html);

foreach($doc->getElementsByTagName('p') as $para){
  // Get existing style
  if($para->hasAttribute('style')){
    $currStyle = $para->getAttribute('style');
    $para->removeAttribute('style');
  } else {
    $currStyle="";
  }

  // Perform whatever operations on the style you want.

  // comletely replace existing style.
  $para->setAttribute('style','your style string here');
}
$newdoc = $doc->saveHTML();

PHP 参考是here

【讨论】:

    【解决方案2】:

    有像 inline styler 这样的工具,旨在使所有 CSS 内联用于电子邮件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-10
      • 2014-02-05
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 2013-09-15
      • 2021-12-30
      • 2017-10-29
      相关资源
      最近更新 更多