CrownGuides

Categories

Guides > PHP > Sitemap generator

Sitemap generator

In this guide we are going to make a small php code for creating a dynamic sitemap. When and why do we need this?.

Google and other search engines likes to have a sitemap to follow if you have a site with complex site with alot of pages/articles and so on.

We are going to make the script able to take a array of paths like "example.com/articles/funny.html" and create a file called sitemap.xml that you can post to search engines. in this guide we are just using a array but in real world senario you would use this to make the sitemap from a database where the content changes frequently

1. We start with making a CLASS that makes this happend

We create a class that will have all the functions that we need

class SiteMap
{

}

Next we need to define som variables that we need inside the class

  private $last_changed = "";
  private $URL = "";
  private $root = "";
  private $debval = "0";

These will be populated with filepaths. and so on

Then we create a __construct funktion where we get the document root for the script

  function __construct() {
   $this->root = $_SERVER["DOCUMENT_ROOT"]; 	
  }

 The only thing we do here is to give the $root variable the path of the files.

After that we need a few functions that populates the other variables with information lite website adress, sitemap filename and then we make a function that works as a debug if we want to print some information as we go on.

  public function SETURL($url) {
  	$this->URL = $url;	
  }
  
  public function SETDEBUG($value) {
  	$this->debval = $value;
  }
  
  public function DEBUG($text) {
  	if ($this->debval == 1) {
			print $text;
		}
  }
  
  public function SETXML($url) {
  	$this->last_changed = $this->root."/".$url;
  }

Now we need to have a function that checks if the sitemap file exists, if not it will create this and. otherwise we check when the sitemap was last edited

  private function Changed() {
  	if (!file_exists($this->last_changed)) {
  		$file = fopen($this->last_changed, "w");
  		$changedtime = strtotime('-18 hours');
		} else {
  		$changedtime = filemtime($this->last_changed);
  	}
  		return $changedtime;
  }

Next we make a function that gets the information about the last change and if the file is more than 18 hours old

  public function TimeToRenew() {
  	$time = $this->Changed();
  	if ($time <= strtotime('-18 hours')) {
  		return true;
  	} else {
  		return false;
  	}
  }

And last function that we need in our CLASS is a function that takes all the urls and converts them to XML and last but not least we will overwrite the old sitemap file.

  public function WriteXML($links) {
  	$list = "";
		$list .= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		// JUST SO MY EDITOR DOSENT SCREW UPP CODE COLORS  <?
		$list .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";
		for ($i=0;$i<sizeof($links); $i++) {
			$list .= "<url><loc>".$this->URL.$links[$i]."</loc></url>";
		}
		$list .= "</urlset>";
		if (is_writable($this->last_changed)) {
			file_put_contents($this->last_changed, $list);
			return $list;
		}  	
  }

 

2. Lets make the code that uses the class we just created 

Now when we have finished our CLASS we need to set all the variables and pass trough all the urls

We make a array of links just for test purpose. you will need to get these from the database. Dont start with / because we fix that in the website url

$static[] = array("Articles/", "Articles/First/", "Articles/Second/");
for($i=0;$i<sizeof($static[0]);$i++) { $array[] = $static[0][$i]; }

Now when we have a array of urls we need to initiate the class and set our variables that we need

// Initiate the CLASS
$obj = new SiteMap;
// Define the URL to the website
$url = $obj->SETURL("http://www.example.com/");
// Define the file where sitemap should be printed
$xml = $obj->SETXML("sitemap.xml");
// Define if we should be in debug mode 1 = Print 0 = Silent
$deb = $obj->SETDEBUG(0);

Then we check to se if it is time to make a new sitemap or not.

// Check if it is time to print the map
$istime = $obj->TimeToRenew();

We now need to check if $istime is true. if it is we make our new sitemap else we do nothing.

if ($istime === true) {
	// Write the sitemap to file
	$write = $obj->WriteXML($array);
	// JUST FOR TESTING PURPOSE
	$obj->DEBUG("Start writing sitemap<br>");
	$obj->DEBUG($write);
	$obj->DEBUG("<br>End of sitemap");
} else { $obj->DEBUG("It is not time to write it yet.."); }

Make sure that you pass the correct $array variable that contains your url

3. How does the whole code look like if you have not read any of this and just want the code?

<?
/*
This class takes a array of site urls and convert them to a XML file that acts as sitemap for GOOGLE ROBOT
SETUP
	- SET DEBUG TO 1 IF YOU WANT TO GET SOM INFO
	- SET THE SETURL WITH THE ADRESS TO YOUR SITE example.com/ DONT FORGET THE SLASH AT THE END
	- SET THE SETXML WITH THE FILENAME OF THE XML FILE sitemap.xml or what you like
	- IF YOU WANT YOU CAN CREATE THE sitemap.xml FILE BUT IF THE FOLDER IS WRITABLE IT SHOULD TAKE CARE OF IT BY IT SELF
USAGE
	- CALL TimeToRenew() TO CHECK IF IT IS MORE THAN 18 HOURS SINCE THE LAST UPDATE OF THE FILE
	- IF TimeToRenew() IS TRUE WE CALL WriteXML($array) WITH THE ARRAY OF SITE LINKS WITH DIFFERENT DYNAMIC CONTENT FOM DATABASE  
*/

class SiteMap
{
  private $last_changed = "";
  private $URL = "";
  private $root = "";
  private $debval = "0";
  
  function __construct() {
   $this->root = $_SERVER["DOCUMENT_ROOT"]; 	
  }
  
  public function SETURL($url) {
  	$this->URL = $url;	
  }
  
  public function SETDEBUG($value) {
  	$this->debval = $value;
  }
  
  public function DEBUG($text) {
  	if ($this->debval == 1) {
			print $text;
		}
  }
  
  public function SETXML($url) {
  	$this->last_changed = $this->root."/".$url;
  }
  
  private function Changed() {
  	if (!file_exists($this->last_changed)) {
  		$file = fopen($this->last_changed, "w");
  		$changedtime = strtotime('-18 hours');
		} else {
  		$changedtime = filemtime($this->last_changed);
  	}
  		return $changedtime;
  }
  
  public function TimeToRenew() {
  	$time = $this->Changed();
  	if ($time <= strtotime('-18 hours')) {
  		return true;
  	} else {
  		return false;
  	}
  }
  
  public function WriteXML($links) {
  	$list = "";
		$list .= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		// JUST SO MY EDITOR DOSENT SCREW UPP CODE COLORS  <?
		$list .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";
		for ($i=0;$i<sizeof($links); $i++) {
			$list .= "<url><loc>".$this->URL.$links[$i]."</loc></url>";
		}
		$list .= "</urlset>";
		if (is_writable($this->last_changed)) {
			file_put_contents($this->last_changed, $list);
			return $list;
		}  	
  }
  
}
// START GETTING THE ARRAY OF LINKS
$static[] = array("Articles/", "Articles/First/", "Articles/Second/");
for($i=0;$i<sizeof($static[0]);$i++) { $array[] = $static[0][$i]; }	
// END OF GETTING THE ARRAY LINKS

// Initiate the CLASS
$obj = new SiteMap;
// Define the URL to the website
$url = $obj->SETURL("http://www.crownguides.com/");
// Define the file where sitemap should be printed
$xml = $obj->SETXML("sitemap.xml");
// Define if we should be in debug mode 1 = Print 0 = Silent
$deb = $obj->SETDEBUG(0); 
// Check if it is time to print the map
$istime = $obj->TimeToRenew();
if ($istime === true) {
	// Write the sitemap to file
	$write = $obj->WriteXML($array);
	// JUST FOR TESTING PURPOSE
	$obj->DEBUG("Start writing sitemap<br>");
	$obj->DEBUG($write);
	$obj->DEBUG("<br>End of sitemap");
} else { $obj->DEBUG("It is not time to write it yet.."); }
?>

Dont forget to have writing permission to the folder where you are going to store your sitemap file. or you could create your sitemap.xml by your self and make the file writable if you want.

Thanks for reading and hope this helps someone.

Comments