2011-05-06 77 views
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最后保持不变。


SOLUTIONcbuckley得到荣誉,但这里是我最后的工作代码:

$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(); 
+0

我猜你的if语句获得通过了作为'FALSE' - 也许是因为原始的字符串缺少你正在寻找的属性。我建议同时测试'$ width'和'$ height'作为'NULL'。 – 65Fbef05 2011-05-06 17:04:30

+0

这不是问题。设置后,我可以回显'$ img-> getAttribute('width')',并且值在那里。 – Sonny 2011-05-06 17:07:37

回答

3

的Zend_Dom_Query对象包含内容的字符串作为其“文件”。你寻找的文件是另一个对象;它在Zend_Dom_Query_Result对象$imgs中返回,因此改用$imgs->getDocument()

您也可以直接与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();