Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two DOMDocument nodes

<table>
<tr>
    <th>Year</th>
    <th>Score</th>
</tr>
<tr>
    <td>2014</td>
    <td>3078</td>
</tr>
</table>

If I have the above table being successfully stored as a variable, how could I append it to a div with an overflow-x style attribute?

I've tried the following snippet but no cigar:

$div = str_get_html('<div style="overflow-x:auto;"></div>');

$div = $div->find('div');

$div = $div->appendChild($table);

return $div;

so expected output should be:

<div style="overflow-x:auto;">
<table>
    <tr>
        <th>Year</th>
        <th>Score</th>
    </tr>
    <tr>
        <td>2014</td>
        <td>3078</td>
    </tr>
</table>
</div>
like image 667
D.Wells Avatar asked Jun 02 '26 20:06

D.Wells


1 Answers

Hope this one will give you a basic idea of implementation. Here we are using DOMDocument.

Try this code snippet here

<?php

ini_set('display_errors', 1);

//creating table node

$tableNode='<table><tr><th>Year</th><th>Score</th></tr><tr><td>2014</td><td>3078</td></tr></table>';

$domDocument = new DOMDocument();
$domDocument->encoding="UTF-8";
$domDocument->loadHTML($tableNode);
$domXPath = new DOMXPath($domDocument);
$table = $domXPath->query("//table")->item(0);

//creating empty div node.

$domDocument = new DOMDocument();
$element=$domDocument->createElement("div");
$element->setAttribute("style", "overflow-x:auto;");

$result=$domDocument->importNode($table,true);//importing node from of other DOMDocument
$element->appendChild($result);
echo $domDocument->saveHTML($element);
like image 125
Sahil Gulati Avatar answered Jun 05 '26 12:06

Sahil Gulati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!