2017-10-05 28 views
0

Mon éditeur WYSIWYG (Summernote) me rapproche de ce dont j'ai besoin pour envoyer des emails encodés en HTML, sauf qu'il utilise les largeurs CSS et les hauteurs au lieu de img largeur et hauteur les attributs.Modification de html en PHP dom - Modification de l'attribut CSS en 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>'; 
} 
?> 

Presque là. Sortie ci-dessus:

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

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

J'ai juste besoin de savoir comment trouver les attributs appropriés img et leurs valeurs, mais comment puis d'écrire ces attributs de nouveau dans les balises img?

+0

est dans les docs ... http://php.net/manual/fr/domdocument.createattribute.php – cmorrissey

Répondre

0

J'ai abandonné la méthode dom et j'ai trouvé cela. Fonctionne très bien.

$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>