1

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!

6
  • What do you mean by "SOME of the images" ? Which img tags are you trying to modify ? Commented Feb 8, 2013 at 19:56
  • It looks like your code does exactly what you want. Just use $html = $doc->saveXML() at the end to get everything in the modified DOM. Commented Feb 8, 2013 at 19:57
  • I need to replace the existing image tags based on the DB returned data that has id attribute. Commented Feb 8, 2013 at 19:58
  • @Barmar I can get the new image tag (with ID $newImageTag variable), but I don't know how to replace that to the existing html string. Commented Feb 8, 2013 at 19:59
  • setAttribute modifies the DOM, and saveHTML converts it back to HTML. Commented Feb 8, 2013 at 20:00

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

What did I do differently from you that made the difference?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.