【发布时间】:2014-03-30 16:58:28
【问题描述】:
简而言之,这就是我想要做的:
- 从文档中获取所有
<img>标签 - 设置
data-src属性(用于延迟加载) - 清空它们的源(用于延迟加载)
- 在这张图片之后注入
<noscript>标签
1-3 没问题。我只是无法将创建的<noscript> 标签正确地放在图像旁边。
我正在尝试使用 insertBefore,但我愿意接受建议:
// Create a DOMDocument instance
$dom = new DOMDocument;
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
// Loads our content as HTML
$dom->loadHTML($content);
// Get all of our img tags
$images = $dom->getElementsByTagName('img');
// How many of them
$len = count($images);
// Loop through all the images in this content
for ($i = 0; $i < $len; $i++) {
// Reference this current image
$image = $images->item($i);
// Create our fallback image before changing this node
$fallback_image = $image->cloneNode();
// Add the src as a data-src attribute instead
$image->setAttribute('data-src', $src);
// Empty the src of this img
$image->setAttribute('src', '');
// Now prepare our <noscript> markup
// E.g <noscript><img src="foobar.jpg" /></noscript>
$noscript = $dom->createElement("noscript");
$noscript->appendChild( $fallback_image );
$image->parentNode->insertBefore( $noscript, $image );
}
return $dom->saveHTML();
页面中有两张图片,结果如下(为清楚起见,缩写):
之前:
<div>
<img />
<p />
</div>
<p>
<img />
</p>
之后:
<div>
<img /> <!-- this should be the fallback wrapped in <noscript> that is missing -->
<p>
<img />
</p>
</div>
<p>
<img /> <!-- nothing happened here -->
</p>
使用$dom->appendChild 有效,但<noscript> 标记应位于图像旁边,而不是文档末尾。
我的 PHP 技能非常生疏,因此我将不胜感激任何澄清或建议。
更新
刚刚意识到saveHTML() 也添加了<DOCTYPE><html><body> 标签,所以我添加了preg_replace(直到找到更好的解决方案)来处理删除它。
另外,我之前粘贴的输出是基于 Chrome 开发者工具的检查器。
我检查了viewsoure 以了解实际情况(并因此了解了该标签)。
这就是真正正在发生的事情: https://eval.in/114620
<div>
<img /> </noscript> <!-- wha? just a closing noscript tag -->
<p />
</div>
<p>
<img /> <!-- nothing happened here -->
</p>
【问题讨论】:
-
为什么不用simplehtmldom类来解析dom??????
-
@yonessafari 使用第三方库将是最后的手段
-
如果您想将
<img />包装在<noscript>中,为什么要使用insertBefore。这个答案可能会有所帮助:stackoverflow.com/a/873166/979455 -
几个关注点:你从来没有定义你的 $src (这是故意的吗?),并且用你的例子运行你的简化测试用例可以确保你的两个图像都包含在
-
我还发现计数没有正确实现——count() 总是返回一,确保总是只有一次迭代。要获取数组的长度,请使用 $images->length.