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

时间:2015-03-06 04:09:00

标签: php xpath

我有一些通过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. 添加课程.lazy
  2. 从原始data-src属性
  3. 添加src属性
  4. src属性修改为blank.gif
  5. 我正在尝试以下但是它无效:

    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");
    }
    

    但它不起作用。

1 个答案:

答案 0 :(得分:1)

你确定吗?以下适用于我。

<?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();