1

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!

hakre
  • 193,403
  • 52
  • 435
  • 836
FlyingCat
  • 14,036
  • 36
  • 119
  • 198

1 Answers1

3

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • +1; Also right comment about xpath, it's superfluous in this case. – hakre Aug 27 '13 at 22:25
  • It works as expect but it seems like my table cell has no border. I add $table->setAttribute('style','border:2px solid #8C8C8C;text-align:center;table-layout:fixed; border-collapse:separate;') and only the table itself has border but not the table cell. I am not sure what happened +1 – FlyingCat Aug 27 '13 at 22:52
  • @FlyingCat: Border is not inherited by child elements. You can use CSS to easily apply border to all cells, but with inline styles you need to apply it to each cell individually. – Jon Aug 27 '13 at 23:19