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!
$html = $doc->saveXML()at the end to get everything in the modified DOM.setAttributemodifies the DOM, andsaveHTMLconverts it back to HTML.