【问题标题】:PHP DOM - How to insert element in a specific position?PHP DOM - 如何在特定位置插入元素?
【发布时间】:2014-03-30 16:58:28
【问题描述】:

简而言之,这就是我想要做的:

  1. 从文档中获取所有<img>标签
  2. 设置data-src 属性(用于延迟加载)
  3. 清空它们的源(用于延迟加载)
  4. 在这张图片之后注入<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-&gt;appendChild 有效,但&lt;noscript&gt; 标记应位于图像旁边,而不是文档末尾。

我的 PHP 技能非常生疏,因此我将不胜感激任何澄清或建议。

更新

刚刚意识到saveHTML() 也添加了&lt;DOCTYPE&gt;&lt;html&gt;&lt;body&gt; 标签,所以我添加了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 使用第三方库将是最后的手段
  • 如果您想将&lt;img /&gt; 包装在&lt;noscript&gt; 中,为什么要使用insertBefore。这个答案可能会有所帮助:stackoverflow.com/a/873166/979455
  • 几个关注点:你从来没有定义你的 $src (这是故意的吗?),并且用你的例子运行你的简化测试用例可以确保你的两个图像都包含在
  • 我还发现计数没有正确实现——count() 总是返回一,确保总是只有一次迭代。要获取数组的长度,请使用 $images->length.

标签: php html dom


【解决方案1】:

已解决

这就是我修复它的方法: https://eval.in/117959

我认为在新节点被插入到 DOM 之后使用它们是个好主意:

$noscript = $dom->createElement("noscript");
$noscriptnode = $image->parentNode->insertBefore( $noscript, $image );

// Only now work with noscript by adding it's contents etc...

当它使用“insertBefore”插入时 - 保存它的引用是个好主意。

$noscriptnode = $image->parentNode->insertBefore( $noscript, $image );

还有一件事:我在 Wordpress 中运行这段代码。之后运行了一些钩子,这弄乱了我的标记。

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2021-09-24
    • 2011-03-22
    相关资源
    最近更新 更多