2011-08-16 36 views
0

我有一些帶有圖像的文字。 例如像這樣更改圖像的src參數內的一些數據並將超鏈接添加到圖像PHP DOM

texttext<img src="2011-08-15/4/img/123.JPG" alt="" width="528" height="394.3458646616541" >texttext 

現在我需要一些代碼,搜索圖像,發現它,檢查其是否具有類。 如果沒有,然後我想改變它的soruce從這個

2011-08-15/4/img/123.JPG 

這個

2011-08-15/4/mini/123.JPG 

然後從IMG標記添加超鏈接,圖像加上刪除的寬度和高度參數,可以使最終的結果一定是像這樣

texttext<a href="2011-08-15/4/img/123.JPG" class="colorbox cboxElement" style="margin: 0 5px 5px 0"><img src="2011-08-15/4/mini/123.JPG" alt=""></a>texttext 

這是搜索的代碼,我需要的是執行所有操作的代碼。

$doc = new DOMDocument(); 
$doc->loadHTML($article_header); 

$imgs = $doc->getElementsByTagName('img'); 
foreach ($imgs as $img) { 
    if(!$img->getAttribute('class')){ 
     // ......Here must be some code that does all the work...... 
     $article_header = $doc->saveXml(); 
    } 
} 

有沒有辦法解決這個問題?如果你不能寫出整個代碼,也許你可以用小例子來幫助我?

  1. 如何更改src參數內的內容並保存。
  2. 如何從img標籤中刪除寬度和高度參數。
  3. 如何將超鏈接標籤添加到im標籤。

我需要這3個技術

回答

1
$doc = new DOMDocument(); 
$doc->loadHTML($html); 

$imgs = $doc->getElementsByTagName('img'); 
foreach ($imgs as $img) { 
    if(!$img->getAttribute('class')){ 
     $src = $img->getAttribute('src'); 
     $newSRC = str_replace('/img/', '/mini/', $src); 
     $img->setAttribute('src', $newSRC); 

     $img->setAttribute('width', '500'); // set new attribute value 
     $img->setAttribute('height', '500'); // set new attribute value 

     $img->setAttribute('title', 'New title'); // set new attribute and value 

     $img->removeAttribute('width'); // remove attribute 
     $img->removeAttribute('height'); // remove attribute 

     $href = $doc->createElement('a', ''); 
     $addhref = $img->parentNode->insertBefore($href, $img); 
     $href->setAttribute('href', 'http://www.google.com'); 

     $img->parentNode->removeChild($img); 
     $href->appendChild($img); 

    } 
} 

echo $doc->saveXml(); 
  1. 線圈圖像
  2. 讓那些沒有類
  3. 變化SRC,寬,高任何你想要的,刪除屬性...
  4. add a元素img元素
  5. 添加href屬性,任何你想要的
  6. 刪除img元素與無級
  7. 追加imga
+0

非常感謝,開始實施此技術爲我的項目。怎麼樣從img標籤中刪除寬度和高度參數?你有setAttribute認爲哪些改變屬性值,但是如何刪除屬性? – David

+0

@David閱讀帖子...''img-> removeAttribute('width');''..我在裏面設置了代碼:) –

+0

Oh sorry。我的錯。謝謝你。我認爲這是我的問題的完整答案。謝謝! – David