I am using PHP and I have an HTML string that contains a string. I need to delete all rows of the table (In reality, there would be some logic to check if to delete the row but for now I am deleting all the rows).
I am trying to delete all the rows from the table but only alternate rows are getting deleted.
$html_string = <<<HTML
<div class="my-table-div">
<div class="clear"></div>
<div class="table-wrap">
<table id="my-table" class="my-class">
<thead>
<tr>
<th class="manage-column" scope="col">Col1</th>
<th class="manage-column" scope="col">Col2</th>
<th class="manage-column" scope="col">Col3</th>
<th class="manage-column" scope="col">Col4</th>
<th class="manage-column" scope="col">Col5;</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Item 1</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>Item 2</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>Item 3</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>Item 4</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
HTML
$doc = new DOMDocument();
$doc->loadHTML($html_string);
$table = $doc->getElementsByTagName('table')[0];
$trs = $table->getElementsByTagName('tr');
for( $x=1; $x<count($trs); $x++ ) {
$trs[$x]->parentNode->removeChild($trs[$x]);
}
//var_dump($doc->saveHTML()); // to check output of the above code
Actual Result after doing above:
Col1 Col2 Col3 Col4 Col5
Item 2
Item 4
Expected Result:
Col1 Col2 Col3 Col4 Col5