【问题标题】:Editing html in PHP dom - Changing CSS to Img attribute在 PHP dom 中编辑 html - 将 CSS 更改为 Img 属性
【发布时间】:2018-03-17 13:07:18
【问题描述】:

我的所见即所得编辑器(Summernote)让我非常接近发送带有图像的 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 标签中呢?

【问题讨论】:

标签: php html css dom domdocument


【解决方案1】:

我放弃了 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 2011-11-23
    • 2011-08-18
    相关资源
    最近更新 更多