I want to loop through images in an HTML document and set the width/height if they don't exist.
Here's a minimal piece of working code:
$content = '<img src="example.gif" />';
$dom = new Zend_Dom_Quer开发者_如何学Goy($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();
The setAttribute()
calls set the values, and I've verified that by echoing the values. The problem is that the DOMElement
is not getting written back to the Zend_Dom_Query
object. The $content
variable is unchanged at the end.
SOLUTION: cbuckley gets the credit, but here is my final working code:
$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();
Doing it with 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();
The Zend_Dom_Query object holds your content string as its "document". The document you seek is in another object; it's returned in the Zend_Dom_Query_Result object $imgs
, so use $imgs->getDocument()
instead.
You could also do it with direct DOM manipulation:
$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();
精彩评论