2011-12-08 14 views
7

Tengo un documento html grande, con varias imágenes. Quiero envolver todas las imágenes dentro de div.wrapped. ¿Cómo haría esto con DOMDocument?Ajustar todas las imágenes con un div usando DOMDocument

He visto el método appendChild, pero eso solo agrega elementos al final. ¿Cómo puedo insertar uno en el medio y luego mover la imagen dentro de él?

Respuesta

22

nunca he usado DomDocument antes, pero creo que quiere decir algo como esto:

$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

impresionante. gracias – DevDonkey

+0

increíble hermano! ¡Rock! –

Cuestiones relacionadas