簡體   English   中英

使用PHP編輯和操作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. 添加類.lazy
  2. 從原始src屬性添加data-src 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM