2011-05-06 11 views
5

Quiero recorrer las imágenes en un documento HTML y configurar el ancho/alto si no existen.Escribir cambios Volver a un objeto Zend Dom Query

Aquí es una pieza mínima de código de trabajo:

$content = '<img src="example.gif" />'; 
$dom = new Zend_Dom_Query($content); 
$imgs = $dom->query('img'); 
foreach ($imgs as $img) { 
    $width = (int) $img->getAttribute('width'); 
    $height = (int) $img->getAttribute('height'); 
    if ((0 == $width) && (0 == $height)) { 
     $img->setAttribute('width', 100)); 
     $img->setAttribute('height', 100); 
    } 
} 
$content = $dom->getDocument(); 

Las llamadas setAttribute() establecen los valores, y he comprobado que haciendo eco de los valores. El problema es que el DOMElement no se vuelve a escribir en el objeto Zend_Dom_Query. La variable $content no se modifica al final.


SOLUCIÓN: cbuckley se lleva el crédito, pero aquí es mi código de trabajo final:

$doc = new DOMDocument(); 
$doc->loadHTML($content); 
foreach ($doc->getElementsByTagName('img') as $img) { 
    if ((list($width, $height) = getimagesize($img->getAttribute('src'))) 
      && (0 === (int) $img->getAttribute('width')) 
      && (0 === (int) $img->getAttribute('height'))) { 
     $img->setAttribute('width', $width); 
     $img->setAttribute('height', $height); 
    } 
} 
$content = $doc->saveHTML(); 

Hacerlo con Zend_Dom_Query:

$dom = new Zend_Dom_Query($content); 
$imgs = $dom->query('img'); 
foreach ($imgs as $img) { 
    if ((list($width, $height) = getimagesize($img->getAttribute('src'))) 
      && (0 === (int) $img->getAttribute('width')) 
      && (0 === (int) $img->getAttribute('height'))) { 
     $img->setAttribute('width', $width); 
     $img->setAttribute('height', $height); 
    } 
} 
$content = $imgs->getDocument()->saveHTML(); 
+0

supongo que su sentencia if es conseguir pasó sobre como FALSE - Tal vez porque la cadena original se carece de los atributos que busca . También recomendaría probar '$ width' y' $ height' para 'NULL'. – 65Fbef05

+0

Ese no es el problema. Puedo repetir '$ img-> getAttribute ('width')' después de configurarlo, y el valor está ahí. – Sonny

Respuesta

3

El objeto Zend_Dom_Query mantiene su cadena de contenido como su "documento". El documento que busca está en otro objeto; se devuelve en el objeto Zend_Dom_Query_Result $imgs, por lo tanto, utilice $imgs->getDocument().

También puede hacerlo con la manipulación directa de DOM:

$doc = new DOMDocument(); 
$doc->loadXml($content); 

foreach ($doc->getElementsByTagName('img') as $img) { 
    $width = (int) $img->getAttribute('width'); 
    $height = (int) $img->getAttribute('height'); 

    if (0 === $width && 0 === $height) { 
     $img->setAttribute('width', '100'); 
     $img->setAttribute('height', '100'); 
    } 
} 

$content = $doc->saveXML(); 
Cuestiones relacionadas