doukuang8166 2012-05-30 12: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 12: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++;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?