Skip to content

Instantly share code, notes, and snippets.

@ekariz
Created September 6, 2023 00:33
Show Gist options
  • Save ekariz/4b3a827a2fa0991683791e1ff0a65d23 to your computer and use it in GitHub Desktop.
Save ekariz/4b3a827a2fa0991683791e1ff0a65d23 to your computer and use it in GitHub Desktop.
php clone table rows and replace cell values
<?php
$html = '<table class="samples">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>30</td>
</tr>
</tbody>
</table>
';
// Replacement data for cells
$replacementData = [
['Alice', '29'],
['Bob', '32'],
['Eve', '27']
];
// Create a new DOMDocument
$dom = new DOMDocument();
$dom->loadHTML($html);
// Create a DOMXPath object to query the DOM
$xpath = new DOMXPath($dom);
// Find all tables with class name "samples"
$tables = $xpath->query('//table[@class="samples"]');
foreach ($tables as $table) {
// Find the table body
$tableBody = $xpath->query('tbody', $table)->item(0);
// Find the rows to be replaced
$originalRows = $xpath->query('tbody/tr', $table);
foreach ($originalRows as $key => $originalRow) {
// Clone the original row and insert it
for ($i = 0; $i < count($replacementData); $i++) {
$clonedRow = $originalRow->cloneNode(true);
// Replace cell contents with replacement data
$cells = $clonedRow->getElementsByTagName('td');
foreach ($cells as $index => $cell) {
$cell->nodeValue = $replacementData[$i][$index];
}
$tableBody->appendChild($clonedRow);
}
}
}
// Display the modified HTML
echo $dom->saveHTML();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment