eire web design home page contact eire-web design eire web design and development site map
stepping on in business
• Welcome to Eire Web Design Ireland

Archive for February, 2008

Sitemap generator class

Thursday, February 21st, 2008

This php class will help you generate a sitemap for your website automatically.

// sitemap generator class
class Sitemap{  // constructor receives the list of URLs to include in the sitemap  

  function Sitemap($items = array()){  

    $this->_items = $items;  

  } // add a new sitemap item  

  function addItem($url, $lastmod = '', $changefreq = '', $priority = '', $additional_fields = array()){  

  $this->_items[] = array_merge(array('loc' => $url, 'lastmod' => $lastmod,'changefreq' => $changefreq,'priority' => $priority), $additional_fields);  

  }  

// get Google sitemap  

  function getGoogle(){  

    ob_start();  

    header('Content-type: text/xml');  

    echo '';  

    echo '';  

  foreach ($this->_items as $i){  

      echo '';  

  foreach ($i as $index => $_i){  

        if (!$_i) continue;  

  echo "<$index>" . $this->_escapeXML($_i) . "";  

      }  

      echo '';  

    }  

    echo '';  

    return ob_get_clean();  

  }  

// get Yahoo sitemap  

 function getYahoo(){  

 	ob_start();  

 	header('Content-type: text/plain');  

  foreach ($this->_items as $i){  

 		  echo $i['loc'] . "\n";  

 		}  

 	return ob_get_clean();  

 }  

// escape string characters for inclusion in XML structure  

 function _escapeXML($str){  

 	$translation = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);  

  foreach ($translation as $key => $value){  

  $translation[$key] = '&#' . ord($key) . ';';  

 		}  

  $translation[chr(38)] = '&';  

  return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&" , strtr($str, $translation));  

 }  

}

Usage:

$s = new Sitemap(); 
 $s->addItem("http://www.websiteurl.com", date("Y-m-d"), 'weekly', '1.0');  

 $s->addItem("http://www.websiteurl.com/link2", date("Y-m-d"), 'weekly', '1.0');  

 $s->addItem("http://www.websiteurl.com/link3", date("Y-m-d"), 'weekly', '1.0');

This class can create two type of sitemaps for you – XML for Google and TEXT for Yahoo

if(isset($_GET['target'])){  

  if(($target = $_GET['target']) == 'google'){  

  echo $s->getGoogle();//xml sitemap  

  }elseif($target == 'yahoo'){  

  echo $s->getYahoo();//txt sitemap  

  }  

}

This class wasn’t designed by me but by Jaimie Sirovich & Cristian Darie and the reason I put it up here is to help others that are trying to get this done without the headache of creating a new code.

Links...

Chicklets...
  • http://www.eire-webdesign.ie/blog/feed/
    http://www.eire-webdesign.ie/blog/feed/
    Google Reader or Homepage
    Add to My Yahoo!
    Subscribe with Bloglines
    Subscribe in NewsGator Online
    add to msn
    Add to My AOL
    Add to Technorati Favorites!
    pageflakes
    windows live