PHP DOM - 替换THEAD到TH标签中的TD标签

时间:2015-03-04 02:19:18

标签: php html domdocument

我正在尝试替换THEAD到TH标签内的所有TD标签。

我认为使用PHP DOM扩展是最好的。我对此很陌生,所以我为自己缺乏知识而道歉。

我做了一些搜索,并找到了如何替换标签名称。但是,我无法弄清楚如何仅替换父项中的标记名称(在本例中为THEAD标记)。我想将TD保留在TBODY中。

这是我的代码,缩小到THEAD内的TD。那就是我迷路的地方。

如何将THEAD中的标签名称更改为TH?

$html = '<table>
    <thead>
        <tr>
            <td>Column 1</td>
            <td>Column 2</td>
            <td>Column 3</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Column 1</td>
            <td>Column 2</td>
            <td>Column 3</td>
        </tr>
        <tr>
            <td>Column 1</td>
            <td>Column 2</td>
            <td>Column 3</td>
        </tr>
        <tr>
            <td>Column 1</td>
            <td>Column 2</td>
            <td>Column 3</td>
        </tr>
    </tbody>
</table>';

// create empty document 
$document = new DOMDocument();

// load html
$document->loadHTML(html);

// Get theads
$theads = $document->getElementsByTagName('thead');

// Loop through theads (incase there are more than one!)
for($i=0;$i<$theads->length;$i++) {
    $thead = $theads->item($i);

    // Loop through TR
    foreach ($thead->childNodes AS $tr) {
      if ($tr->nodeName == 'tr') {

          // Loop through TD
          foreach ($tr->childNodes AS $td) {
              if ($td->nodeName == 'td') {

                // Replace this tag

                }
            }

      }
    }

}

1 个答案:

答案 0 :(得分:1)

如果您已查看过该手册,则可以使用->replaceChild()方法将td替换为th代码:

$html = '<table>
    <thead>
        <tr>
            <td>Column 1</td>
            <td>Column 2</td>
            <td>Column 3</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Column 1</td>
            <td>Column 2</td>
            <td>Column 3</td>
        </tr>
        <tr>
            <td>Column 1</td>
            <td>Column 2</td>
            <td>Column 3</td>
        </tr>
        <tr>
            <td>Column 1</td>
            <td>Column 2</td>
            <td>Column 3</td>
        </tr>
    </tbody>
</table>';

// create empty document
$document = new DOMDocument();
// load html
$document->loadHTML($html);
// Get theads
$theads = $document->getElementsByTagName('thead')->item(0); // get thead tag
foreach($theads->childNodes as $tr) { // loop thead rows `tr`
    $tds = $tr->getElementsByTagName('td'); // get tds inside trs
    $i = $tds->length - 1;
    while($i > -1) {
        $td = $tds->item($i); // td
        $text = $td->nodeValue; // text node
        $th = $document->createElement('th', $text); // th element with td node value
        $td->parentNode->replaceChild($th, $td); // replace
        $i--;
    }

}

echo $document->saveHTML();

Doc notes

Sample Output