5
我想循环浏览HTML文档中的图像,并设置宽度/高度(如果它们不存在)。写回到Zend Dom查询对象
这里有一个最小的一块工作代码:
$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();
的setAttribute()
呼叫通过回值设置的值,我验证过。问题是DOMElement
没有写回到Zend_Dom_Query
对象。变量$content
最后保持不变。
SOLUTION:cbuckley得到荣誉,但这里是我最后的工作代码:
$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();
做这与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();
我猜你的if语句获得通过了作为'FALSE' - 也许是因为原始的字符串缺少你正在寻找的属性。我建议同时测试'$ width'和'$ height'作为'NULL'。 – 65Fbef05 2011-05-06 17:04:30
这不是问题。设置后,我可以回显'$ img-> getAttribute('width')',并且值在那里。 – Sonny 2011-05-06 17:07:37