Friday, June 12, 2026
HomeLanguagesPHP | DOMDocument createDocumentFragment() Function

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.




<?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();
?>


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




<?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();
?>


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

RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS