Php 将更改写回Zend Dom查询对象

Php 将更改写回Zend Dom查询对象,php,zend-framework,dom,Php,Zend Framework,Dom,我想循环浏览HTML文档中的图像,如果它们不存在,则设置宽度/高度 下面是一段最小的工作代码: $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

我想循环浏览HTML文档中的图像,如果它们不存在,则设置宽度/高度

下面是一段最小的工作代码:

$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();
$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\u Dom\u 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();

Zend_Dom_查询对象将您的内容字符串作为其“文档”保存。你寻找的文件在另一个物体中;它是在Zend\u Dom\u Query\u结果对象
$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();

我猜您的if语句被传递为
FALSE
——可能是因为原始字符串缺少您要查找的属性。我还建议对
NULL
测试
$width
$height
。这不是问题所在。设置后,我可以回显
$img->getAttribute('width')
,值就在那里。