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