FlyingCat
FlyingCat

Reputation: 14290

Replace existing image tags within html string with new image

I am trying to replace existing image tags with new image tag wiht id attribute.

I have DB returned htmlstring like

<div>
<p>random p</p>
<img src='a.jpb'/>
</div>
<span>random span</span>
<img src='b.jpb'/>

more...

I want to replace 'SOME' of the images with id attribute for example:

replacing

<img src='a.jpb'/>

to

<img id='123' src='a.jpb'/>

I use domdocument

$doc = new DOMDocument();

          $doc->loadHTML($html);

          $imageTags = $doc->getElementsByTagName('img');

          $imgSource=$this->DBimgSource;
          $id=$this->DBID;

          foreach($imageTags as $tag) {
              //getting all the images tags from $html string
              $source=$tag->getAttribute('src');

           if(!empty($imgSource) && !empty($source)){
             if(in_array($source, $imgSource)){

              $id=array_search($source,$imgSource);
              $imgID=$id;
              $tag->setAttribute('id',$imgID);
              $newImageTag=$doc->saveXML($tag);

              //I am not sure how to replace existing image tags within $html with the $newImageTag                

              }
            }
          }

Any ideas how to do this? I couldn't think of anyway. Thanks for the help!

Upvotes: 1

Views: 1886

Answers (1)

Barmar
Barmar

Reputation: 782683

This works for me:

$html = "<html><body><img src='foo.jpg'/></body></html>";
$doc = new DOMDocument();
$doc->loadHTML($html);
$img = $doc->getElementsByTagName('img')->item(0);
$img->setAttribute('id', 'newId');
$html = $doc->saveHTML();
echo $html;

Output is:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><img src="foo.jpg" id="newId"></body></html>

Upvotes: 2

Related Questions