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', '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.
Output the XML: Output the XML content using the saveXML() function.
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.
i’m Saturn , i interested in the field of SEO and research and review of the latest techniques and methods in the world of SEO. You can read my content every day on inbatio.com