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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?