将更改写入Zend Dom查询对象 [英] Writing Changes Back to a Zend Dom Query Object
问题描述
我想循环使用HTML文档中的图像,并设置宽度/高度(如果它们不存在)。
I want to loop through images in an HTML document and set the width/height if they don't exist.
这里是一小段工作代码: / p>
Here's a minimal piece of working code:
$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
变量在结尾不变。
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.
解决方案: cbuckley 获得信用,但这里是我的最终工作代码:
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();
使用 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();
推荐答案
Zend_Dom_Query对象将您的内容字符串作为其文档。你所寻求的文件是另一个对象;它在Zend_Dom_Query_Result对象 $ imgs
中返回,因此使用 $ imgs-> getDocument()
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.
您还可以使用直接DOM操作:
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();
这篇关于将更改写入Zend Dom查询对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!