A Simple PHP/XML Sitemap Generator

XML Sitemaps are a useful method for search engines to quickly pick up new content they would otherwise have to find via hyperlinks on the web. Sitemaps can also provide useful metadata regarding URLs such as its last modification date, how often the content changes and the relative importance of the URL in comparison to the rest of the site.

The following code allows you to easily maintain an XML sitemap using PHP. You can:

  • Generate a sitemap from scratch
  • Add URLs to the sitemap
  • Edit URL’s metadata in the sitemap
  • Delete URLs from the sitemap

The script is very simple and currently only takes into account a URL and its last modification date, with the latter being optional. This allows you to easily populate the sitemap with existing and new URLs and easily indicate when content has been updated. You do not have to worry about adding duplicate files as the DOM takes care of itself there.

If you have a large number of URLs, you will need to tinker the script to accommodate more than one sitemap, which would simply mean passing a unique filename into the invocation of the class instance.

Simply save the contents of the two scripts below and try it for yourself. The references to Sitemap.xml assume that you are in your domain’s root directory, otherwise, you should ensure your Sitemap.xml is saved in the root directory to avoid complications, unless it is referenced in a sitemap index file.

Example code to populate a sitemap

Example on how to update the last modified value

Leave a Reply

Your email address will not be published. Required fields are marked *