How can DomDocument be used to manipulate HTML tables in PHP?
To manipulate HTML tables in PHP using DomDocument, you can load the HTML content into a DomDocument object, locate the table you want to manipulate using XPath queries, and then make changes to the table structure or content as needed. This approach allows you to programmatically modify the HTML table without directly manipulating the raw HTML code.
<?php
$html = '<table>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
</tr>
</table>';
$dom = new DomDocument();
$dom->loadHTML($html);
$xpath = new DomXPath($dom);
$tableRows = $xpath->query('//table//tr');
foreach ($tableRows as $row) {
$cells = $row->getElementsByTagName('td');
foreach ($cells as $cell) {
$cell->nodeValue = 'Modified ' . $cell->nodeValue;
}
}
echo $dom->saveHTML();
?>