2017-10-05 58 views
0

我的所見即所得編輯器(Summernote)讓我非常接近需要發送帶編碼圖像的HTML編碼電子郵件,除了它使用CSS寬度和高度代替img寬度和高度屬性。在PHP DOM中編輯html - 將CSS更改爲Img屬性

<?php 
$html = '<p><img src="image1.png" style="width: 770px; height:300px;"><br></p> 
<p><img src="image2.png" style="width: 300px;"><br></p>'; 

$dom = new DOMDocument; 
$dom->loadHTML($html); 

$imgs = $dom->getElementsByTagName('img'); 
foreach ($imgs as $img) { 
    foreach ($img->attributes as $attr) { 
     $name = $attr->nodeName; 
     $value = $attr->nodeValue; 
     echo "Attribute '$name' :: '$value'<br />"; 
    } 
    echo '<br>'; 
} 
?> 

幾乎在那裏。以上輸出:

Attribute 'src' :: 'image1.png' 
Attribute 'style' :: 'width: 770px; height:300px;' 

Attribute 'src' :: 'image2.png' 
Attribute 'style' :: 'width: 300px;' 

我只需要弄清楚如何拿出適當的IMG屬性和它們的值,但如何然後這些屬性寫回的img標籤?

+0

它在文檔中... http://php.net/manual/en/domdocument.createattribute.php – cmorrissey

回答

0

我放棄了dom方法,想出了這個。很棒。

$message = '<p><img src="email_attachments/image1.png" style="width: 770px; height:300px;"> 
1234567890</p><p><img src="email_attachments/image2.png" style="width: 50%;"><br></p>'; //incoming html from SummerNote 

$pos = 0; //starting position 
for ($i = 1; $i <= substr_count($message, '<img '); $i++) { //loop through the images 

    $locStart = strpos($message, '<img ', $pos); //starting position of this image tag 
    $locEnd = strpos($message, '>', $locStart); //end of this image tag 
    $pos = $locEnd; //set starting position for next image, if any 

    $tag = substr($message, $locStart, ($locEnd-($locStart-1))); //this is just the image tag 

    $widthStart = strpos($tag, 'width: '); // start of width value in the inline css, i.e., 100px or 25% 
    $widthEnd = strpos($tag, ';', $widthStart); //end of width value 

    $width = substr($tag, $widthStart, ($widthEnd-($widthStart-1))); //just the value of the css width 
    $width = str_replace('width: ', '', $width); // replace 'width: ' 
    $width = str_replace('px;', '', $width);  // replace 'px;' 
    $width = str_replace(';', '', $width);  // replace ';' if % is used 

    $message = substr_replace($message, ' width="'.$width.'" ', $locEnd, 0); //add width value to the image tag  
} 
$message = str_replace('src="email_attachments/', 'src="cid:', $message); //change the folder name to cid 

result is: <p><img src="cid:image1.png" style="width: 770px; height:300px;" width="770" > 
1234567890</p><p><img src="cid:image2.png" style="width: 50%;" width="50%" ><br></p>