Reputation: 5612
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?
Upvotes: 5
Views: 9920
Reputation: 76646
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();
}
Upvotes: 13
Reputation: 3540
Use foreach to loop through all elements.
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();
}
Upvotes: 0
Reputation: 318
foreach ($tags as $tag)
{
$old_src = $tag->getAttribute('src');
$new_src_url = 'website.com/assets/'.$old_src;
$tag->setAttribute('src', $new_src_url);
}
Upvotes: 0
Reputation: 5977
You can just loop through all the tags and replace them. Not tested!
$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);
$doc->saveHTML($tag);
}
Upvotes: 0