I receive HTML table from jquery summernote like this
<div class="pasted">
<table class="table table-bordered" style="width: 100%;">
<tbody>
<tr>
<td>
item 1
</td>
</tr>
</tbody>
</table>
</div>
Now i want to convert to this using PHP
<div class="pasted">
<div class="table-responsive">
<table class="table table-bordered table-summernote1">
<tbody>
<tr>
<td>
item 1
</td>
</tr>
</tbody>
</table>
</div>
</div>
Here is my PHP Code:
<?php
$dom = new DOMDocument();
$dom->loadHTML($text, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$b = $dom->getElementsByTagName('table');
foreach ( $b as $t )
{
if ( $t->hasAttributes() )
{
foreach ( $t->attributes as $attr )
{
$t->removeAttribute($attr->nodeName);
}
$t->removeAttribute("style");
$t->setAttribute('class', 'table table-bordered table-summernote1');
$responsive = $dom->createElement('div');
$t->insertBefore($responsive);
$responsive->setAttribute('class', 'table-responsive');
$frag = $t->cloneNode(true);
$responsive->appendChild($frag);
}
}
?>
PHP code does not work. page hangs on $responsive->appendChild($frag) and processing is never ended.
I have also tried with preg_replace but does not work
foreach ( $b as $t )
{
if ( $t->hasAttributes() )
{
foreach ( $t->attributes as $attr )
{
$t->removeAttribute($attr->nodeName);
}
$t->removeAttribute("style");
}
}
$text = $dom->saveHTML();
$text = preg_replace('/<table>(.*)<\/table>/isum', '<div class="table-responsive"><table class="table table-bordered table-summernote1">$1</table></div>', $text);
It will convert just first 1 or 2 tables. if there are multiple tables, one table goes into another table.
what is the better solution to solve this?