webSIGHTdesigns - Web Design, Web Development, Web Hosting

How to Create a Dynamic Sitemap for CakePHP

Posted on Monday, June 30th, 2014 at 10:22 pm
by webSIGHTdesigns

Create a dynamic sitemap XML file to submit your site's URLs to search engines.

In this tutorial we will explain how to use PHP to create a dynamic sitemap.xml file in your website's web root in order to submit your site's URLs to search engines.

First we need to create the file sitemap.xml.php in our website's root directory:

<?php header("Content-type: text/xml"); ?>
<?php echo '<?'; ?>xml version="1.0" encoding="UTF-8"<?php echo '?'; ?>>
<?php echo '<?'; ?>xml-stylesheet type="text/xsl" href="http://www.domain.com/sitemap.xsl"<?php echo '?'; ?>>
<urlset 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" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.domain.com/</loc>
<lastmod><? echo date('c',time()); ?></lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>http://www.domain.com/posts</loc>
<lastmod><? echo date('c',time()); ?></lastmod>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>http://www.domain.com/portfolio</loc>
<lastmod><? echo date('c',time()); ?></lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>http://www.domain.com/hosting</loc>
<lastmod><? echo date('c',time()); ?></lastmod>
<changefreq>monthly</changefreq>
<priority>0.3</priority>
</url>
<url>
<loc>http://www.domain.com/development</loc>
<lastmod><? echo date('c',time()); ?></lastmod>
<changefreq>monthly</changefreq>
<priority>0.3</priority>
</url>
<?php
	// set up your mysql connection
	$mysqli = new mysqli('localhost', 'username', 'password', 'database');
	// check mysql connection
	if (mysqli_connect_errno()) {
		printf("Connect failed: %s\n", mysqli_connect_error());
		exit();
	}
	// sql query
	$sql = "SELECT `id`, `slug`, `publish_date` FROM `posts` WHERE `published`='1'";
	// if connection succeeds
	if ($result = $mysqli->query($sql)) {
		//$num_rows = $result->num_rows;
		// if there are rows returned
		//if($num_rows) {
			// loop through the result set
			while($row = $result->fetch_assoc()) {
?><url>
<loc>http://www.domain.com/posts/view/<?php echo $row['slug']; ?></loc>
<lastmod><? echo date('c',strtotime($row['publish_date'])); ?></lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<?php
			}
			// free the result set from memory
			$result->close();
		//}
	}
	// close the mysql connection
	$mysqli->close();
?>
</urlset>

As you can see, we have set up our static pages manually, and then we loop through all the rows in the posts table to dynamically generate URLs for our blog posts. Next we need to create a sitemap.xsl file in our website's root directory:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
                xmlns:html="http://www.w3.org/TR/REC-html40"
                xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="html" version="1.0" encoding="UTF-8" indent="yes"/>
	<xsl:template match="/">
		<html xmlns="http://www.w3.org/1999/xhtml">
			<head>
				<title>XML Sitemap</title>
				<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
				<style type="text/css">
					body {
						font-family:"Lucida Grande","Lucida Sans Unicode",Tahoma,Verdana;
						font-size:13px;
					}

					#intro {
						background-color:#CFEBF7;
						border:1px #2580B2 solid;
						padding:5px 13px 5px 13px;
						margin:10px;
					}

					#intro p {
						line-height:	16.8667px;
					}

					td {
						font-size:11px;
					}

					th {
						text-align:left;
						padding-right:30px;
						font-size:11px;
					}

					tr.high {
						background-color:whitesmoke;
					}

					#footer {
						padding:2px;
						margin:10px;
						font-size:8pt;
						color:gray;
					}

					#footer a {
						color:gray;
					}

					a {
						color:black;
					}
				</style>
			</head>
			<body>
				<h1>XML Sitemap</h1>
				<div id="intro">
					<p>
						Say something about this sitemap here.
					</p>
				</div>
				<div id="content">
					<table cellpadding="5">
						<tr style="border-bottom:1px black solid;">
							<th>URL</th>
							<th>Priority</th>
							<th>Change Frequency</th>
							<th>LastChange (GMT)</th>
						</tr>
						<xsl:variable name="lower" select="'abcdefghijklmnopqrstuvwxyz'"/>
						<xsl:variable name="upper" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
						<xsl:for-each select="sitemap:urlset/sitemap:url">
							<tr>
								<xsl:if test="position() mod 2 != 1">
									<xsl:attribute  name="class">high</xsl:attribute>
								</xsl:if>
								<td>
									<xsl:variable name="itemURL">
										<xsl:value-of select="sitemap:loc"/>
									</xsl:variable>
									<a href="{$itemURL}">
										<xsl:value-of select="sitemap:loc"/>
									</a>
								</td>
								<td>
									<xsl:value-of select="concat(sitemap:priority*100,'%')"/>
								</td>
								<td>
									<xsl:value-of select="concat(translate(substring(sitemap:changefreq, 1, 1),concat($lower, $upper),concat($upper, $lower)),substring(sitemap:changefreq, 2))"/>
								</td>
								<td>
									<xsl:value-of select="concat(substring(sitemap:lastmod,0,11),concat(' ', substring(sitemap:lastmod,12,5)))"/>
								</td>
							</tr>
						</xsl:for-each>
					</table>
				</div>
				<div id="footer">
					Generated for <a href="http://www.domain.com/" title="My Website">My Website</a>.
				</div>
			</body>
		</html>
	</xsl:template>
</xsl:stylesheet>

The sitemap.xsl document specifies styles to apply to your generated sitemap.xml document. Lastly, you need to set up your .htaccess file to allow requests for sitemap.xml to display the results of the sitemap.xml.php script:

<IfModule mod_rewrite.c>
   RewriteEngine on

   RewriteRule sitemap\.xml sitemap.xml.php [L]

   RewriteCond %{REQUEST_FILENAME} -f [OR]
   RewriteCond %{REQUEST_FILENAME} -d
   RewriteRule ^.*$ - [S=40]

   RewriteRule ^$ app/webroot/ [L]
   RewriteRule (.*) app/webroot/$1 [L]
</IfModule>

The above example is an .htaccess file for CakePHP, but you could use the RewriteRule line that mentions sitemap.xml before other .htaccess rules as well.

Please Sign In

Please sign in to post a comment.

Web Development

View details »

Web Hosting

View details »

Our Portfolio

View portfolio »

WebSight Designs webSIGHTdesigns preferred email webSIGHTdesigns United States United States