doukuang8166 2012-05-30 20:03
浏览 46
已采纳

PHP textContent删除HTML?

I have the following script which loops through a HTML table and gets the values from it then returns the value of the table in a td.

$tds = $dom->getElementsByTagName('td');

                // New dom
                $dom2 = new DOMDocument;

                $x = 1;
                // Loop through all the tds printing the value with a new class
                foreach($tds as $t) {
                    if($x%2 == 1)
                        print "</tr><tr>";

                    $class = ($x%2 == 1) ? "odd" : "even";

                    var_dump($t->textContent);

                    print "<td class='$class'>".$t->textContent."</td>";
                    $x++;
                }

But the textContent seems to be stripping the HTML tags (for example it is a <p></p> wrapper tag). How can I get it to just give me the value?

Or is there another way of doing this? I have the following html

<table>
<tr>
<td>q1</td>
<td>a1</td>
</tr>
<tr>
<td>q2</td>
<td>a2</td>
</tr>
</table>

and I need to make it look like

<table>
<tr>
<td class="odd">q1</td>
<td class="even">a1</td>
</tr>
<tr>
<td class="odd">q2</td>
<td class="even">a2</td>
</tr>
</table>

It will always look the exact same way (minus extra element rows and the values which change).

Any help?

  • 写回答

1条回答 默认 最新

  • dongpao9437 2012-05-30 20:20
    关注

    According to MDN this is the expected behaviour of textContent.

    You can just add the class to the tds in the DomDocument

    $tds = $dom->getElementsByTagName('td');
    $x = 1;
    foreach($tds as $td) {
        if($x%2 == 1){
            $td->setAttribute('class', 'odd');
        }
        else{
            $td->setAttribute('class', 'even');
        }
        $x++;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算