【发布时间】:2013-12-06 01:53:13
【问题描述】:
我有这样的页面链接:
import.html
<h1>Title</h1>
<img src="img/pic1.jpg" alt="" title="Picture 1" class="pic">
<img src="img/pic2.jpg" alt="" title="Picture 2" class="pic">
<img src="img/pic3.jpg" alt="" title="Picture 3" class="pic">
<p>random text</p>
<img src="img/pic4.jpg" alt="" title="Picture 4" class="pic">
index.php
<?php
//get file content
$html = file_get_contents('import.html');
function replace_img_src($img_tag) {
$doc = new DOMDocument();
$doc->loadHTML($img_tag);
$tags = $doc->getElementsByTagName('img');
if (count($tags) > 0) {
$tag = $tags->item(0);
$old_src = $tag->getAttribute('src');
$new_src_url = 'website.com/assets/'.$old_src;
$tag->setAttribute('src', $new_src_url);
return $doc->saveHTML($tag);
}
return false;
}
// usage
$new = replace_img_src($html);
print_r(htmlspecialchars($new));
目标:
我想用新的图片链接替换 import.html 文件和 return file 中 img 元素的 all src 属性.我设法创建替换一个元素。
如何编辑它以遍历整个文件并替换所有属性并return new import.html 替换为src's?
【问题讨论】:
-
通常你应该在获取元素后使用 foreach 循环并将其保存在 $tags 变量中。像 foreach($tags as $tag) 之类的东西。但我不确定 $tags 变量中有什么。当你运行代码时你看到了什么 var_dump($tags); ?