Friday, September 5, 2025
HomeLanguagesPHP | DOMDocumentFragment appendXML() Function

PHP | DOMDocumentFragment appendXML() Function

The DOMDocument::appendXML() function is an inbuilt function in PHP which is used to append raw XML data to a DOMDocumentFragment.

Syntax:

bool DOMDocumentFragment::appendXML( string $data )

Parameters: This function accepts a single parameter $data which holds the XML to append.

Return Value: This function returns TRUE on success or FALSE on failure.

Below given programs illustrate the DOMDocument::appendXML() function in PHP:

Program 1:




<?php
  
// Create a new DOMDocument
$doc = new DOMDocument;
  
// Load the XML
$doc->loadXML("<root/>");
  
// Create a Document Fragment
$f = $doc->createDocumentFragment();
  
// Append the XML to fragment
$f->appendXML(
  "<h1>Heading 1</h1><strong>Strong text</strong>");
  
// Append the fragment to document
$doc->documentElement->appendChild($f);
  
// Save the XML
echo $doc->saveXML(); 
?>


Output:

<?xml version="1.0"?>
<root><h1>Heading 1</h1><strong>Strong text</strong></root>

Program 2:




<?php
  
// Create a new DOMDocument
$doc = new DOMDocument;
  
// Load the XML
$doc->loadXML("<root/>");
  
// Create a Document Fragment
$f = $doc->createDocumentFragment();
  
// Append the XML to fragment
$f->appendXML("<h1 style=\"color: red\"> Red </h1>");
$f->appendXML("<h1 style=\"color: green\"> Green </h1>");
$f->appendXML("<h1 style=\"color: blue\"> Blue </h1>");
  
// Append the fragment to document
$doc->documentElement->appendChild($f);
  
// Save the XML
echo $doc->saveXML(); 
?>


Output:

<?xml version="1.0"?>
<root>
    <h1 style="color: red"> Red </h1>
    <h1 style="color: green"> Green </h1>
    <h1 style="color: blue"> Blue </h1>
</root>

Reference: https://www.php.net/manual/en/domdocumentfragment.appendxml.php

RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS