$dom = new DOMDocument(); $fragment = $dom->createDocumentFragment(); $fragment->appendXML(''); $dom->appendChild($fragment); echo $dom->saveHTML();Hello world!
Hello world!
element to the fragment. Finally, we append the fragment to the existing DOM document using the appendChild method, and then output the updated HTML using the saveHTML method.
Example 2:
In this example, we'll dynamically generate a table using a DOMDocumentFragment:
$dom = new DOMDocument(); $fragment = $dom->createDocumentFragment(); $table = $dom->createElement('table'); $thead = $dom->createElement('thead'); $tbody = $dom->createElement('tbody'); // Append the table header row $tr = $dom->createElement('tr'); $tr->appendChild($dom->createElement('th', 'Name')); $tr->appendChild($dom->createElement('th', 'Email')); $thead->appendChild($tr); // Append the table body rows $data = [ ['John Doe', 'john.doe@example.com'], ['Jane Smith', 'jane.smith@example.com'], ['Bob Johnson', 'bob.johnson@example.com'], ]; foreach ($data as $row) { $tr = $dom->createElement('tr'); $tr->appendChild($dom->createElement('td', $row[0])); $tr->appendChild($dom->createElement('td', $row[1])); $tbody->appendChild($tr); } $table->appendChild($thead); $table->appendChild($tbody); $fragment->appendChild($table); $dom->appendChild($fragment); echo $dom->saveHTML();
Name | |
---|---|
John Doe | john.doe@example.com |
Jane Smith | jane.smith@example.com |
Bob Johnson | bob.johnson@example.com |