2011-12-08 62 views
7

我有一個大的html文檔,有幾個圖像。我想將div.wrapped中的所有圖像包起來。我如何與DOMDocument做這個?使用DOMDocument包裝所有圖像

我見過appendChild方法,但只在最後附加元素。我如何在中間插入一個,然後將圖像移入其中?

回答

22

我從來沒有使用DOM文檔,但我想你的意思是這樣的:

$html = <<<EOF 
<html> 
    <head> 
     <title>:(-> :)</title> 
    </head> 
    <body> 
     <img src="www.com" /> 
     <div class="random"> 
      <img src="www.ru" /> 
     </div> 
    </body> 
</html> 
EOF; 

$dom = new DOMDocument(); 
$dom->loadHTML($html); 

//Create new wrapper div 
$new_div = $dom->createElement('div'); 
$new_div->setAttribute('class','wrapper'); 

//Find all images 
$images = $dom->getElementsByTagName('img'); 

//Iterate though images 
foreach ($images AS $image) { 
    //Clone our created div 
    $new_div_clone = $new_div->cloneNode(); 
    //Replace image with this wrapper div 
    $image->parentNode->replaceChild($new_div_clone,$image); 
    //Append this image to wrapper div 
    $new_div_clone->appendChild($image); 
} 
+0

真棒。謝謝 – DevDonkey

+0

驚人的兄弟!你搖滾! –