Created
September 6, 2023 00:32
-
-
Save ekariz/2bdd11c191b55906a3c036973d0f47f9 to your computer and use it in GitHub Desktop.
clone table rows in php DOMDocument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$html = '<table border="1"> | |
<tr> | |
<td>property</td> | |
<td>specification</td> | |
</tr> | |
<tr> | |
<td>Data 1</td> | |
<td>Data 2</td> | |
</tr> | |
<tr> | |
<td>Data 3</td> | |
<td>Data 4</td> | |
</tr> | |
<tr> | |
<td>Data 3</td> | |
<td>Data 4</td> | |
</tr> | |
<tr> | |
<td>Data 3</td> | |
<td>Data 4</td> | |
</tr> | |
<tr> | |
<td>Data 3</td> | |
<td>Data 4</td> | |
</tr> | |
</table>'; | |
// Load the HTML document | |
$doc = new DOMDocument(); | |
$doc->loadHTML($html); | |
// Create a DOMXPath object | |
$xpath = new DOMXPath($doc); | |
// Find the table element (assuming it's the first table in this example) | |
$table = $xpath->query('//table')->item(0); | |
// Find the row(s) where you want to add new columns (e.g., the first row) | |
// $rows = $xpath->query('//tr[2]', $table); | |
// $rows = $xpath->query('//tr[position() = 1 or position() = 2 or position() = 3]', $table); | |
// $rows = $xpath->query('//tr', $table); | |
$rows = $xpath->query('//table//tr'); | |
// Create and append new <td> elements (columns) to the selected row(s) | |
foreach ($rows as $row) { | |
$newColumn = $doc->createElement('td'); | |
$newColumn->textContent = 'New Column 1'; | |
$row->appendChild($newColumn); | |
$newColumn = $doc->createElement('td'); | |
$newColumn->textContent = 'New Column 2'; | |
$row->appendChild($newColumn); | |
$newColumn = $doc->createElement('td'); | |
$newColumn->textContent = 'New Column 3'; | |
$row->appendChild($newColumn); | |
} | |
// Save or display the modified HTML | |
echo $doc->saveHTML(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment