Click here to Skip to main content
15,896,269 members
Articles / Programming Languages / PHP

Generate a Google SiteMap with PHP

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
4 May 2012CPOL4 min read 46.6K   1.1K   18  
An article demonstrating how to create an automatically updated Google SiteMap using PHP
<?php
	// Sets the file header to show this is an XML file
	header("Content-type: text/xml");
	
	// The xml header is written this way to avoid the <? tags being seen as code
	// by PHP (a problem if short_open_tag == 1)
	echo('<?xml version="1.0" encoding="UTF-8"?>');
	
	// Set this to true to ignore all files beginning with .
	$respectUnixHidden = true;
	// Modify this to ignore specific files, delimited by ';'
	$filesToIgnore = 'sitemap.php;sitemap.pl;error_log;temp.php';
	// Modify this to ignore all files with specific file extensions, 
	// delimited by ';'
	$extensionsToIgnore = 'xml;html;shtml;inc;css;txt';
	// This is added in front of all the found filenames to produce URLs instead
	// of local filenames. For example, if $rootUrl is http://www.google.com, 
	// index.htm will become http://www.google.org.uk/index.htm
	$rootUrl = 'http://www.freetools.org.uk/';
	
	// An array containing the files to be ignored
	$ignoreFiles = explode(';', $filesToIgnore);
	// An array containing the extensons to be ignored
	$ignoreExtensions = explode(';', $extensionsToIgnore);
	echo('<urlset xmlns="http://www.google.com/schemas/sitemap/0.9">');
	
	// Opens the directory the file is stored in and checks it is open
	if ($localDir = opendir('.'))
	{
		// Iterates through each file in the local directory
		while (false !== ($file = readdir($localDir)))
		{
			// Extracts the extension
			$extension = end(explode('.', $file));
			// Checks the filename and extension against the ignore lists
			if (!is_dir($file) and !(in_array($file, $ignoreFiles)) 
			                   and !(in_array($extension, $ignoreExtensions))
							   and !($respectUnixHidden == true and $file[0] == '.'))
			{
				echo('<url>');
				echo('<loc>');
				// Echoes the URL of the file by combining the filename and $rootUrl
				echo("{$rootUrl}{$file}");
				echo('</loc>');
				echo('<lastmod>');
				// Echoes the date the file was last modified in YYY-MM-DD form
				echo(date('Y-m-d', filemtime($file)));
				echo('</lastmod>');
				echo('</url>');
			}
		}
	}
?>
</urlset>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions