How to Create and Save XML File using PHP

XML stands for Extensible Markup Language which is used for store and transport data. Some web project needs to store products, user, or other information in the XML file. In those projects, you should need to generate XML data or convert PHP array to XML, then create and save the XML file using PHP. Also, XML format is commonly used in sitemap of the website.

In this tutorial, we’ll show the simple way to generate XML file using PHP. You can use XML DOM Parser to process XML document in PHP. Also, using saveXml() and save() method you’ll be able to output XML document to the browser and save XML document as a file.

  • The saveXml() function puts internal XML document into a string.
  • The save() function puts internal XML document into a file.

The following example PHP code will create XML sitemap and save XML file into the xml/ directory.

$xmlString '<?xml version="1.0" encoding="UTF-8"?>
    <urlset  xmlns:xsi=""  xmlns:image=""  xsi:schemaLocation=""  xmlns="">

$dom = new DOMDocument;
$dom->preserveWhiteSpace FALSE;

//Save XML as a file

Use the following PHP code to output XML document on the browser.

//View XML document
$dom->formatOutput TRUE;

Leave a reply

CodexWorld Newsletter

Subscribe CodexWorld updates via email and get every new post delivered to your inbox.