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:

Step1:

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.

Step2:

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");

Step3:

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', 'http://www.sitemaps.org/schemas/sitemap/0.9');

$xml->appendChild($urlset);

// Add URLs to the XML

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

// Example:

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

$urlset->appendChild($url);

$loc = $xml->createElement('loc', 'https://www.example.com/page1');

$url->appendChild($loc);

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

$url->appendChild($lastmod);

After placing this script in your code, you should replace https://www.example.com/page1 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