Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php replace all src atributes of img in file

Tags:

html

dom

php

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?

like image 334
Ing. Michal Hudak Avatar asked Nov 21 '13 14:11

Ing. Michal Hudak


1 Answers

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();
}
like image 89
Amal Murali Avatar answered Oct 18 '22 03:10

Amal Murali