0

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 Answer 1

0

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++;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.