AZee
AZee

Reputation: 520

Replace PHP DOM Element

I want to replace third table in php dom object with a new table. I can select it by

$table = $dom->getElementsByTagName('table')->item(3);

I tried

$table->parentNode->appendChild($new_table);

and it says

Catchable fatal error: Argument 1 passed to DOMNode::appendChild() must be an instance of DOMNode, string given in C:\xampp\htdocs\index.php on line 73

Can someone please explain what is wrong with the code or how I can correct it?

$new_table = "<table width='100%' bgcolor='#000'>$table_rows</table>";

Upvotes: 0

Views: 561

Answers (3)

AZee
AZee

Reputation: 520

I got it working by extracting the idea from answers below and some more research.

$table = $dom->getElementsByTagName('table')->item(3);
$new_table = $dom->createDocumentFragment();
$new_table->appendXML("<table width='100%' bgcolor='#EEEEEE'>$table_rows</table>");
$table->parentNode->replaceChild($new_table,$table);

The actual problem was with my $table_rows array that each row contained some extra attributes like "colspan", $nbsp; and some additional tags.

Thank you guys for your interest and support.

Upvotes: 0

Mike Dinescu
Mike Dinescu

Reputation: 55720

You'll have to use createElement to create the table fragment before appending it.

You could also create a fragment from the XML using appendXML and then append that fragment using appendChild

$fragment = $dom->createDocumentFragment();
$fragment->appendXML("<table width='100%' bgcolor='#000'>$table_rows</table>");
// now append the fragment
$table->parentNode->appendChild($fragment);

Here's a working example: http://ideone.com/0Lx742

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

Miky's answer is step 1: you must construct your element as a DOM node.

$new_table = $dom->createElement("table");
$new_table->setAttribute("width","100%");
$new_table->setAttribute("bgcolor","#000");
foreach($table_rows as $row) $new_table->appendChild($row);
// the above assumes $table_rows is an array of TR nodes, not strings!

Step 2 is:

$table->parentNode->replaceChild($new_table,$table);

Upvotes: 0

Related Questions