【问题标题】:php dom - add class on child elementsphp dom - 在子元素上添加类
【发布时间】:2018-03-16 11:48:34
【问题描述】:

我在变量 php .. $html 中有一些 html 内容

我想添加一个类(myClass)只在'img'包括在所有'table'中(不在外面...)

<?php
$html = <<aaa
<img src="..." alt="..." />
<table class="..">
  <tr>
    <td><img src="..." alt="..." /></td>
  </tr>
  <!-- more rows ...  -->
</table>
<!-- other tables with img -->
aaa;

$dom = new DOMDocument();
$dom->loadHTML($html);
$table = $dom->getElementsByTagName('table');
/*
here, I have to find the table_child <img> and add the class myClass Es. <img class="myClass" .. />
*/
/*
store the new content in a new variabile $html_edit
*/
print "$html_edit";
/*
like this:
$html_edit = <<aaa
<img src="..." alt="..." />
<table class="..">
  <tr>
    <td><img class="myClass" src="..." alt="..." /></td>
  </tr>
  <!-- more rows ...  -->
</table>
<!-- other tables with <img class="myClass" -->
aaa;
*/
?>

我该怎么做?

【问题讨论】:

  • 不是重复的,我只想在 'table' 的 'img' 子项中添加类,而不是在 html 中的所有 'img' 中添加类
  • 首先选择表格标签,然后使用该答案申请类。

标签: php dom


【解决方案1】:

考虑一下您的搜索 - 它分为两层 - 首先是查找表格,然后是这些表格中的图像。然后使用the setAttribute() function

$html = <<<EOT
    <img src="..." alt="Outside the Table - No Change" />
    <table class="theTableClass">
      <tr>
        <td><img src="..." alt="The Target Image #1" /></td>
      </tr>
      <tr>
        <td><img src="..." alt="The Target Image #2" /></td>
      </tr>
    </table>
    <img src="..." alt="Outside the Table - No Change Again" />
    <table class="theTableClass">
      <tr>
        <td><img src="..." alt="The Target Image #3" /></td>
      </tr>
      <tr>
        <td>Just Text Here</td>
      </tr>
    </table>
EOT;

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

// First Find each of the TABLEs and Loop
$tables = $dom->getElementsByTagName('table');
foreach ($tables as $k => $table)
{
    // Within Each Table, Find the IMGs and Loop
    $imgs = $table->getElementsByTagName('img');
    foreach ($imgs as $k2 => $img)
    {
        // Set the IMGs Class attribute to whatever you want
        $img->setAttribute('class', 'myClass');
    }
}

// Save the modified HTML back to the variable
$html = $dom->saveHTML();

echo $html;

【讨论】:

  • 非常感谢,如果我使用 $dom->loadHTML($html); 这个解决方案可以正常工作但如果我使用 $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);该类被添加到所有图像中!
  • 那不使用那些额外的设置?还是您对它们有特殊需求?
  • $html 中的内容在数据库中恢复,它是我的 cms 中帖子的内容。那我就不用重新打印文件信息ecc了
猜你喜欢
  • 2016-01-27
  • 1970-01-01
  • 2012-05-31
  • 2020-11-10
  • 1970-01-01
  • 2010-11-10
  • 2013-10-28
  • 2021-02-15
  • 2011-07-29
相关资源
最近更新 更多