PHP DOM Document将整个表复制成一个新的div

时间:2018-01-17 12:17:35

标签: php domdocument

我从jquery summernote接收HTML表格,如此

<div class="pasted">
   <table class="table table-bordered" style="width: 100%;">
      <tbody>
         <tr>
            <td>
              item 1
            </td>
         </tr>
       </tbody>
     </table>
</div>

现在我想使用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>

这是我的PHP代码:

<?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代码不起作用。页面挂起$ responsive-&gt; appendChild($ frag),处理永不结束。

我也尝试过使用preg_replace但不起作用

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);

它只会转换前1或2个表。如果有多个表,则一个表进入另一个表。

解决此问题的最佳解决方案是什么?

1 个答案:

答案 0 :(得分:1)

似乎反对在克隆节点中添加克隆节点。我已经更改了$responsive的添加方式(对表的父级)并删除了$t节点,然后重新添加了克隆。

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->parentNode->insertBefore($responsive, $t);
        $responsive->setAttribute('class', 'table-responsive');

        $frag = $t->cloneNode(true);
        $t->parentNode->removeChild($t);

        $responsive->appendChild($frag);
    }
}