0

There's a html table assigned to a variable $text. (The table can have different number of rows)

What would be the easiest way to get rid of the rows that do not have a value in column 2 (in this example it would be row 2)

Example:

$text = <<<EOT
<table style="width: 430px;">
<tbody>
<tr>
<td style="width: 199px;"><b>Row 1:</b></b></td>
<td style="width: 413px;">6754</td>
</tr>
<tr>
<td style="width: 199px;"><b>Row 2:</b></td>
<td style="width: 413px;"></td>
</tr>
<tr>
<td style="width: 199px;"><b>Row 3</b></td>
<td style="width: 413px;">7567</td>
</tr>
</tbody>
</table>

EOT;

Expected result:

$text = <<<EOT

<table style="width: 430px;">
<tbody>
<tr>
<td style="width: 199px;"><b>Row 1:</b></b></td>
<td style="width: 413px;">6754</td>
</tr>
<tr>
<td style="width: 199px;"><b>Row 3</b></td>
<td style="width: 413px;">7567</td>
</tr>
</tbody>
</table>

EOT;
Mohammad
  • 21,175
  • 15
  • 55
  • 84
smolo
  • 737
  • 1
  • 15
  • 27

1 Answers1

0

I think using DOMXPath is best way to removing target elements from your html. Using xpath you can select trs that seconds td of it is empty.

$doc = new DOMDocument();
$doc->loadHTML($text);
$xpath = new DOMXPath($doc);
$row = $xpath->query("//tr[td[2]='']")->item(0);
$row->parentNode->removeChild($row);
$newText = $doc->saveHTML();

Check it in demo

Mohammad
  • 21,175
  • 15
  • 55
  • 84