Skip to content
Related Articles

Related Articles

Improve Article

PHP | DOMDocument save() Function

  • Last Updated : 29 Aug, 2019

The DOMDocument::save() function is an inbuilt function in PHP which is used to create an XML document from the DOM representation. This function is used after creating the new dom document from scratch.

Syntax:

int DOMDocument::save( string $filename, int $options = 0 )

Parameters: This function accepts two parameters as mentioned above and described below:

  • $filename: This parameter holds the path to save the XML document.
  • $options: This parameter holds the additional options. Currently this parameter supports only LIBXML_NOEMPTYTAG.

Return Value: This function returns the number of bytes written on success or FALSE on failure.

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



Program 1:




<?php
    
// Create a new DOMDocument
$domDocument = new DOMDocument('1.0', 'iso-8859-1');
   
// Set the formatOutput to true
$domDocument->formatOutput = true;
   
// Create an element
$domElement = $domDocument->createElement('organization', 'GeeksforGeeks');
    
// Append element to the document
$domDocument->appendChild($domElement);
    
// Save the XML document
$domDocument->save("abcd.xml");
   
echo "File saved successfully";
    
?>

Output:

File saved successfully

The content of saved file abcd.xml:

<?xml version="1.0" encoding="iso-8859-1"?>
<organization>GeeksforGeeks</organization>

Program 2:




<?php
    
// Create a new DOMDocument
$domDocument = new DOMDocument('1.0', 'iso-8859-1');
    
// Create an element
$domElement1 = $domDocument->createElement('organization');
$domElement2 = $domDocument->createElement('name', 'GeeksforGeeks');
$domElement3 = $domDocument->createElement('address', 'Noida');
$domElement4 = $domDocument->createElement('email', 'abc@geeksforgeeks.org');
    
// Append element to the document
$domDocument->appendChild($domElement1);
$domElement1->appendChild($domElement2);
$domElement1->appendChild($domElement3);
$domElement1->appendChild($domElement4);
    
// Save the XML file
$domDocument->save("g4g.xml");
   
echo "File saved successfully";
    
?>

Output:

File saved successfully

The content of saved file g4g.xml:

<?xml version="1.0" encoding="iso-8859-1"?>
<organization>
    <name>GeeksforGeeks</name>
    <address>Noida</address>
    <email>abc@geeksforgeeks.org</email>
</organization>

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :