How to append element to another element using php

2019-08-28 14:45发布

问题:

This question already has an answer here:

  • DOMDocument append already fixed html from string 1 answer

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.