简体   繁体   中英

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

I have some HTML snippets retrieved through PHP/JSON such as:

<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:

<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
  2. Add data-src attribute from original src attribute
  3. Modify src attribute to 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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