A Simple PHP/XML Sitemap Generator

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.

class sitemap {

	public $filename = 'Sitemap.xml';
	public $dom = null;
	
	public function __construct($filename = '') {
		// You can pass your own filename
		if(trim($filename))
			$this->filename = $filename;
		$this->dom = new DOMDocument;
		$this->dom->preserveWhiteSpace = true;
		// Get the sitemap if it exists, and if it doesn't, generate a basic empty one.
		(!is_file($this->filename) && touch($this->filename) && $this->generate()
		|| @$this->dom->loadXML(file_get_contents($this->filename)));
	}
 
	public function generate() {
		// Generates an empty sitemap 
		$this->dom = new DOMDocument();
		$this->dom->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<urlset
xml:ns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
</urlset>');
	}
 
	public function addrow($array) {
		// Add new rows by passing an array of values, see example
		$urlset = $this->dom->getElementsByTagName('urlset')->item(0);
		$node = $this->dom->createElement('url');
		$node->setAttribute('id',md5($array['loc']));
			
			foreach($array as $key => $var) {
				$node2 = $this->dom->createElement($key);
				$node3 = $this->dom->createTextNode($var);
				$node2->appendChild($node3);
				$node->appendChild($node2);
			}
			
		$newnode = $urlset->appendChild($node);
	}
 
	public function editrow($md5) {
		// Edit an existing row. Rows are uniquely identified by the MD5 of the URL
		$xpath = new DOMXPath($this->dom);
		// In this simple example, it updates the last modified time of the URL
		$mod = $xpath->query("/urlset/url[@id='$md5']/lastmod");
		$mod->item(0)->nodeValue = strftime("%Y-%m-%d",time() - gmmktime() + mktime());
	}
 
	public function deleterow($id) {
		$xpath = new DOMXPath($this->dom);
		$urlset = $this->dom->getElementsByTagName('urlset')->item(0);
		$row = $xpath->query("/urlset/url[@id='$id']")->item(0);
		if($row)
			$row->parentNode->removeChild($row);
	}
	
	public function __destruct() {
		// File is automatically saved when you're finished using the class
		$this->dom->save($this->filename);
	}
}

Example code to populate a sitemap:

$urls = array(
'http://www.example.com/','http://www.example.com/page2','http://www.example.com/page3',
'http://www.example.com/page4','http://www.example.com/page5','http://www.example.com/page6'
);

	foreach($urls as $url) // Iterate through example URLs and add to sitemap
		$_sitemap->addrow(array('loc'=>$url,'lastmod'=>'2010-01-01'));

Example on how to update the last modified value:

$_sitemap = new sitemap('Sitemap.xml');
$_sitemap->editrow(md5('http://www.example.com/page5'));
$_sitemap->editrow(md5('http://www.example.com/page3'));
whoami
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.