用新图像替换html字符串中的现有图像标记

时间:2013-02-08 19:52:11

标签: php domdocument

我正在尝试使用带有id属性的新图像标记替换现有的图像标记。

我有DB返回htmlstring,如

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

more...

我想用id属性替换'SOME'图像,例如:

替换

<img src='a.jpb'/>

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

我使用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                

              }
            }
          }

任何想法如何做到这一点?无论如何我想不出来。谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

这对我有用:

$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;

输出是:

<!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>
相关问题