2013-07-28 85 views
2

我有圖像標籤<img src="path_to_file.png">但我希望圖像標籤轉換爲移動網站中的鏈接。 所以我想IMG轉換爲一個href:如何使用php dom文件刪除和替換標籤

<a href="path_to_file.png" target="_blank">Click here to open in new tab</a> 

我開始使用PHP的DOM。 我可以獲得列出的所有屬性。

$newdocument = new DOMDocument(); 
$newdocument->loadHTML(); 
$getimagetag = $doc->getElementsByTagName('img'); 
foreach($getimagetag as $tag) { 
    echo $src=$tag->getAttribute('src'); 
} 

但我們怎樣才能src屬性,然後徹底去除img標籤,因爲它包含了諸如高度和長度等參數,然後創建鏈接的新標籤?

嗨,大家好,我可以把它從PHP DOM使用下面的代碼

$input="<img src='path_to_file.png' height='50'>"; 
    $doc = new DOMDocument(); 
    $doc->loadHTML($input); 
    $imageTags = $doc->getElementsByTagName('img'); 
    foreach($imageTags as $tag) { 
     $src=$tag->getAttribute('src'); 
     $a=$doc->createElement('a','click here to open in new tab'); 
     $a->setAttribute('href',$src); 
     $a->setAttribute('style','color:red;'); 
     $tag->parentNode->replaceChild($a,$tag); 
     } 
     $input=$doc->saveHTML(); 
echo $input; 

create元素也可以用來放<a></a>即點擊...新標籤之間的文本進行。

replacechild用於刪除$標記,即img並用a標記替換它。 通過設置屬性,我們可以添加其他參數,如風格,目標等

我用PHP DOM到底,因爲我只是想,我從MySQL獲得的數據進行轉換,而不是其他元素,如網站的標誌。當然也可以使用JavaScript。

謝謝

@dave chen爲javascript方式,並指向檢測移動鏈接。

@nate用於指向我的答案。

+0

退房這種重複樣的解決方案:http://stackoverflow.com/a/3195048/2609094 – 2013-07-28 17:13:07

+1

喜感謝代碼...但我想問,如何輸入文本_click在這裏打開** ** – Moz

回答

2

我會建議使用JavaScript這樣做:

<!DOCTYPE html> 
<html> 
<head> 
    <title>Images Test</title> 
    <script> 
     window.onload = changeImages; 

     function changeImages() { 
      var images = document.getElementsByTagName("img"); 

      while (images.length > 0) { 
       var imageLink  = document.createElement("a"); 
       imageLink.href  = images[0].src; 
       imageLink.innerHTML = "Click here to view " + images[0].title; 
       images[0].parentNode.replaceChild(imageLink, images[0]); 
      } 
     } 
    </script> 
</head> 
<body> 
    Here is a image of flowers : <img src="images/flowers.bmp" title="Flowers" ><br> 
    Here is a image of lakes : <img src="images/lakes.bmp"  title="Lakes" ><br> 
    Here is a image of computers: <img src="images/computers.bmp" title="Computers"><br> 
</body> 
</html> 

Example

+1

之間的新tab_嗨,謝謝!我已經完全忘記了javascript也可以使用! – Moz

+1

我想指出http://stackoverflow.com/questions/11381673/javascript-solution-to-detect-mobile-browser檢測手機,並根據此切換您的標籤。 –