如何使用php将元素附加到另一个元素 [英] How to append element to another element using php

查看:77
本文介绍了如何使用php将元素附加到另一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将元素添加到Domdocument中新创建的节点中。

I am trying to append the elements into my new created node in Domdocument.

我有类似

$dom = new DomDocument();
     $dom->loadHTML($html]);
     $xpath=new DOMXpath($dom);
      $result = $xpath->query('//tbody');

      if($result->length > 0){
          $tbody = $dom->getElementsByTagName('tbody');
          $table=$dom->createElement('table');
           $table->appendChild($tbody);
       }

我的身体没有桌子标签,就像

My tbody doesn't have table tag and it is like

<tbody>
    <tr>
       <td>cell</td>
       <td>cell</td>
       <td>cell</td>
    </tr> 
    ….more
</tbody>

我想用包裹它标记。

我的代码不起作用,它给了我类似的错误

My codes don't work and it gave me error like


PHP可捕获的致命错误:传递给DOMNode :: appendChild()的参数1必须是DOMNode的实例,给出了DOMNodeList的实例,

PHP Catchable fatal error: Argument 1 passed to DOMNode::appendChild() must be an instance of DOMNode, instance of DOMNodeList given,

我该如何解决这个问题?谢谢!

How do I solve this issue? Thanks!

推荐答案

变量 $ tbody 不是单个< tbody> 元素;这是元素的集合 -您正在通过标签名称获取元素,并且可以有很多。如果您只想通过标记名称查找元素,也绝对没有理由使用XPath。

The variable $tbody is not a single <tbody> element; it's a collection of elements -- you are "getting elements by tag name", and there can be many. There is also absolutely no reason to use XPath if all you want is to find elements by tag name.

执行以下操作:

$tbodies = $dom->getElementsByTagName('tbody');
foreach ($tbodies as $tbody) {
    $table = $dom->createElement('table');
    $tbody->parentNode->replaceChild($table, $tbody);
    $table->appendChild($tbody);
}

查看实际效果

See it in action.

这篇关于如何使用php将元素附加到另一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆