将更改写回Zend Dom查询对象

Son*_*nny 5 php dom zend-framework

我想循环遍历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();
Run Code Online (Sandbox Code Playgroud)

setAttribute()呼叫通过回值设置的值,我验证过.问题是DOMElement没有写回Zend_Dom_Query对象.的$content变量是在端不变.


解决方案: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();
Run Code Online (Sandbox Code Playgroud)

这样做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();
Run Code Online (Sandbox Code Playgroud)

cmb*_*ley 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();
Run Code Online (Sandbox Code Playgroud)