PHP | DOMDocument createDocumentFragment() Function

The DOMDocument::createDocumentFragment() function is an inbuilt function in PHP which is used to create a new document fragment.

Syntax:

DOMDocumentFragment DOMDocument::createDocumentFragment( void )

Parameters: This function doesn’t accepts any parameters.

Return Value: This function returns a new DOMDocumentFragment or FALSE if an error occurred.

Below programs illustrate the DOMDocument::createDocumentFragment() function in PHP:



Program 1: In this example we will create headings with fragments.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
  
// Create a root element
$dom->loadXML("<root/>");
  
// Create a Fragment
$fragment = $dom->createDocumentFragment();
  
// Append the XML
$fragment->appendXML(
    "<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>");
  
// Append the fragment
$dom->documentElement->appendChild($fragment);
  
echo $dom->saveXML();
?>

chevron_right


Output:

<?xml version="1.0"?>
<root><h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3></root>

Program 2: In this example we will create colored lines

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
  
// Create a root element
$dom->loadXML("<root/>");
  
// Create a Fragment
$fragment = $dom->createDocumentFragment();
  
// Colors
$colors = ['red', 'green', 'blue'];
  
for ($i = 0; $i < 3; $i++) {
    // Append the XML
    $fragment->appendXML(
"<div style='color: $colors[$i]'>This is $colors[$i]</div>");
  
    // Append the fragment
    $dom->documentElement->appendChild($fragment);
}
  
echo $dom->saveXML();
?>

chevron_right


Output:

<?xml version="1.0"?>
<root>
    <div style="color: red">This is red</div>
    <div style="color: green">This is green</div>
    <div style="color: blue">This is blue</div>
</root>

Reference: https://www.php.net/manual/en/domdocument.createdocumentfragment.php




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.