使用 PHP 编辑和操作 class 和 DOM 元素的数据属性

Edit and manipulate class and data-attributes of DOM elements with PHP

我通过 PHP/JSON 检索了一些 HTML 片段,例如:

<div>
  <p>Some Text</p>
  <img src="example.jpg" />
  <img src="example2.jpg" />
  <img src="example3.jpg" />
</div>

我正在用 DOMDocument()xpath 加载它,并希望能够对其进行操作,以便我可以像这样向图像添加延迟加载:

<div>
  <p>Some Text</p>
  <img class="lazy" src="blank.gif" data-src="example.jpg" />
  <img class="lazy" src="blank.gif" data-src="example2.jpg" />
  <img class="lazy" src="blank.gif" data-src="example3.jpg" />
</div>

其中包含:

  1. 添加class.lazy
  2. 从原始 src 属性添加 data-src 属性
  3. 修改src属性为blank.gif

我正在尝试以下但它不起作用:

foreach ($xpath->query("//img") as $node) {
  $node->setAttribute( "class", $node->getAttribute("class")." lazy");
  $node->setAttribute( "data-src", $node->getAttribute("src"));
  $node->setAttribute( "src", "./inc/image/blank.gif");
}

但它不起作用。

你确定吗?以下对我有用。

<?php

$html = <<<EOQ
<div>
  <p>Some Text</p>
  <img src="example.jpg" />
  <img src="example2.jpg" />
  <img src="example3.jpg" />
</div>
EOQ;

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

foreach ($xpath->query('//img') as $node) {
    $node->setAttribute('class', $node->getAttribute('class') . ' lazy');
    $node->setAttribute( "data-src", $node->getAttribute("src"));
    $node->setAttribute( "src", "./inc/image/blank.gif");
}

echo $dom->saveHTML();