This question already has an answer here:
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!
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:
See it in action.