2013-06-23 51 views
1

我有一個HTML編輯器,管理員可以在其中輸入HTML電子郵件的內容,但對於瀏覽器/客戶端之間的一致樣式,需要包含內聯CSS。 E.g一個段落:如何解析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;"> 

我覺得這是一樣的流行的郵件黑猩猩的工作原理是將內嵌樣式,如果他們不存在。

段落只是示例,我也有表格和其他類添加樣式。

+0

我想我可以用簡單的HTML DOM來使用他們的類名居然找到了不同的元素,但我怎麼會去修改內嵌css –

+0

[有什麼工具可以自動內聯CSS樣式來創建電子郵件HTML代碼?](http://stackoverflow.com/questions/791070/what-tools-to-automatically-inline-css-style-to-create -email-HTML代碼) –

回答

3

將文檔加載到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。