I have in page links like this:
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));
Goal:
I want to replace all src
attributes of img
element in import.html file and return file with new image links. I managed to create replace one element.
How to edit this to go through whole file and replace all attributes and return new import.html with replaced src
's?
getElementsByTagName()
method will return a DOMNodeList
object containing all the matched elements. Currently, you're just modifying only one img
tag. To replace all the img
tags, simply loop through them using a foreach
:
function replace_img_src($img_tag) {
$doc = new DOMDocument();
$doc->loadHTML($img_tag);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
$old_src = $tag->getAttribute('src');
$new_src_url = 'website.com/assets/'.$old_src;
$tag->setAttribute('src', $new_src_url);
}
return $doc->saveHTML();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With