2017-10-05 4 views
0

내 WYSIWYG 편집기 (Summernote)는 img 너비와 높이 대신 CSS 너비와 높이를 사용한다는 점을 제외하면 이미지가있는 html로 인코딩 된 전자 메일을 보내는 데 너무 가깝습니다. 속성.PHP dom에서 CSS 편집 - 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>