php dom - 在子元素上添加类

时间:2018-03-16 11:48:34

标签: php dom

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

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

<?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;
*/
?>

我该怎么办?

1 个答案:

答案 0 :(得分: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;