如何将多个图像文档转化为Html文档输出
有时我们需要用php更改动态html字符串中的src。可以将html字符串存储到数据库中,并且在前端显示时更新该字符串的src路径。以下是一种非常简单的示例:
<?php
$htmlString = '<strong>Image One:</strong><br/>
<img src="imageone.png" /><br/>
<strong>Image Two:</strong><br/>
<img src="imagetwo.png" /><br/>
<strong>Image Three:</strong><br/>
<img src="imagethree.png" /><br/>';
$doc = new DOMDocument();
$doc->loadHTML($htmlString);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
$oldSrc = $tag->getAttribute('src');
$newScrURL = 'upload/images/'.$oldSrc;
$tag->setAttribute('src', $newScrURL);
$tag->setAttribute('data-src', $oldSrc);
}
$htmlString = $doc->saveHTML();
print($htmlString);
输出:
<strong>Image One:</strong><br>
<img src="upload/images/imageone.png" data-src="imageone.png"><br>
<strong>Image Two:</strong><br>
<img src="upload/images/imagetwo.png" data-src="imagetwo.png"><br>
<strong>Image Three:</strong><br>
<img src="upload/images/imagethree.png" data-src="imagethree.png"><br>