简体   繁体   English

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

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

I have some HTML snippets retrieved through PHP/JSON such as: 我有一些通过PHP / JSON检索的HTML代码段,例如:

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

I am loading it with DOMDocument() and xpath and would like to be able to manipulate it so I can add lazy loading to the images like so: 我正在使用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>

Which entails: 其中包括:

  1. Add class .lazy 添加类.lazy
  2. Add data-src attribute from original src attribute 从原始src属性添加data-src src属性
  3. Modify src attribute to blank.gif src属性修改为blank.gif

I am trying the following but it isn't working: 我正在尝试以下操作,但不起作用:

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

but it isn't working. 但它不起作用。

Are you sure? 你确定吗? The following works for me. 以下对我有用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM