How to append element to another element using php [duplicate]

偶尔善良 提交于 2019-12-25 13:35:47

问题


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

I have something like

$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>

I wanted to wrap it with a table tag.

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

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!


回答1:


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.

Do this instead:

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

See it in action.



来源:https://stackoverflow.com/questions/18476343/how-to-append-element-to-another-element-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!