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
$dom = new DOMDocument( '1.0' , 'iso-8859-1' );
$dom ->loadXML( "<root/>" );
$fragment = $dom ->createDocumentFragment();
$fragment ->appendXML(
"<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" );
$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
$dom = new DOMDocument( '1.0' , 'iso-8859-1' );
$dom ->loadXML( "<root/>" );
$fragment = $dom ->createDocumentFragment();
$colors = [ 'red' , 'green' , 'blue' ];
for ( $i = 0; $i < 3; $i ++) {
$fragment ->appendXML(
"<div style='color: $colors[$i]'>This is $colors[$i]</div>" );
$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
Last Updated :
20 Feb, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...