How to Generate XML Sitemap for Website in PHP

In this article, we will try to teach you how to automatically generate a sitemap file in PHP.

Using the scripts mentioned below, the sitemap file is created according to the main xml sitemap protocol, and the pages that are added to the website will be included in the sitemap file.

To generate an XML sitemap in PHP website, you can follow these steps:


Create a new PHP file: 

It is better to name your file as sitemap.xml. This name is a common name for a sitemap file and has a significant impact on the quick indexing of website content.


Start the PHP script and set the appropriate header for XML: Begin the PHP script by setting the appropriate header for XML content.

<?php header("Content-type: text/xml");


Create the XML structure: Use PHP’s XML-related functions to create the XML structure for the sitemap.

$xml = new DOMDocument('1.0', 'UTF-8');

// Create the root element

$urlset = $xml->createElement('urlset');

$urlset->setAttribute('xmlns', '');


// Add URLs to the XML

// Loop through your URLs and add each one as a URL element

// Example:

$url = $xml->createElement('url');


$loc = $xml->createElement('loc', '');


$lastmod = $xml->createElement('lastmod', '2023-07-16');


After placing this script in your code, you should replace with the address of your desired page and change 2023-07-16 to the last modification date or creation date of the page.

Final Step:

Output the XML: Output the XML content using the saveXML() function.

echo $xml->saveXML();

You should place the generated sitemap file in the root of your website and specify the path to the sitemap file in the robots.txt file of your site.

note: for websites with a large number of pages (large websites), you should use other methods and save your files with the .gzip extension.

Leave A Comment