Класс для работы с Sitemaps

16 June 2008 – 19:56

Выкладываю самописный класс для работы с Sitemaps. Класс умеет генерировать (SimpleXML) новую sitemap или добавлять в уже существующую позиции из массива ссылок и необязательных параметров (lastmod, changefreq, priority). Умеет уведомлять поисковик о сгенерированной карте (CURL). Пишет лог в БД (через PDO). Позже добавлю еще пару полезных методов. Если что непонятно - спрашивайте. Также приветствуются поправки и рекомендации.

 

Класс:

  1. <?php
  2. /**
  3.  * Sitemap Generator Class
  4.  *
  5.  * @author Alex Zhukoff
  6.  * @license http://creativecommons.org/licenses/by-sa/3.0/ (Creative Commons BY-SA)
  7.  * @version 1.0
  8.  * @link http://zhukoff.com
  9.  */
  10.  
  11. class SitemapGenerator {
  12.  
  13.         private $fsitemap = 'sitemap.xml';
  14.         public $schema = 'http://www.google.com/schemas/sitemap/0.84';
  15.         public $pingstat = 'failed';
  16.         private $dbh = null;
  17.         private $val = null;
  18.         private $del = null;
  19.         public $freq = array("always","hourly","daily","weekly","monthly","yearly","never");
  20.  
  21.         /**
  22.          * SitemapGenerator constructor
  23.          * @param string $fsitemap
  24.          * @param string $schema
  25.          */
  26.         function __construct($fsitemap = null, $schema = null){
  27.                 $this->schema = !$schema ? $this->schema : $schema;
  28.                 $this->cPDO('localhost','mysql','db','root','');
  29.                 if(!is_file($this->fsitemap))$this->createSM();
  30.         }
  31.  
  32.         /**
  33.          * DB connection
  34.          * @param string $h host
  35.          * @param string $s dns
  36.          * @param string $db database
  37.          * @param string $u user
  38.          * @param string $p pass
  39.          * @access private
  40.            */
  41.         private function cPDO($h = '127.0.0.1',$s = 'mysql',$db = 'db',$u = 'root',$p = ''){
  42.                 $this->dbh = new PDO($s.':dbname='.$db.';host='.$h, $u, $p);
  43.         }
  44.  
  45.         /**
  46.          * DB connection
  47.          * @access private
  48.            */
  49.         private function createSM(){
  50.                 file_put_contents($this->fsitemap,$this->wrap());
  51.                 $this->del = 1;
  52.         }
  53.  
  54.                 /**
  55.          * Sitemap file header
  56.          * @access private
  57.            */
  58.         private function wrap(){
  59.                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".
  60.                                 '<urlset xmlns="'.$this->schema.'">'."\n".
  61.                                 '</urlset>';
  62.         }
  63.  
  64.         /**
  65.          * "Add links" wrapper
  66.          * @param mixed $val Could be either an array or an string
  67.            */
  68.         public function addLinks($val = null){
  69.                 try{$this->pAdd($val);}
  70.                 catch(Exception $x){echo $x->getMessage();}
  71.         }
  72.  
  73.         /**
  74.          * Add links
  75.          * @param mixed $val Could be either an array or an string
  76.          * @access private
  77.            */
  78.         private function pAdd($val){
  79.                 if((@$val) &amp;&amp; !is_array(@$val)){$this->val = array($val);}
  80.                 elseif(@$val[0][0] != null){$this->val = $val;}
  81.                 else{throw new Exception("Не передано ни одной ссылки");}
  82.  
  83.                 $load = simplexml_load_file($this->fsitemap);
  84.                 foreach($this->val as $v){
  85.                         $tm = $load->addChild('url');
  86.                         if($this->chkAdd('lnk',$v[0]))$tm->addChild('loc', $v[0]);
  87.                         if($this->chkAdd('lmd',$v[1]))$tm->addChild('lastmod', $v[1]);
  88.                         if($this->chkAdd('chf',$v[2]))$tm->addChild('changefreq', $v[2]);
  89.                         if($v[3] = $this->chkAdd('pri',$v[3]))$tm->addChild('priority', $v[3]);
  90.                 }
  91.                 $tmp = $load->asXML();
  92.                 file_put_contents($this->fsitemap, $tmp);
  93.                 $this->del = null;
  94.                 unset($tmp);
  95.         }
  96.  
  97.         /**
  98.          * Check links
  99.          * @param string $t
  100.          * @param mixed $v Could be either an string or an int
  101.          * @return mixed Could be an string or an int or null
  102.            */
  103.         public function chkAdd($t,$v){
  104.                 switch ($t){
  105.                 case 'lnk':return utf8_encode(htmlentities($v,ENT_QUOTES,"UTF-8"));
  106.                 case 'lmd':return ($v == '')?null:$v;
  107.                 case 'chf':return array_keys($this->freq, $v);
  108.                 case 'pri':return ($v == '')?null:$this->priorIt($v);
  109.                 }
  110.         }
  111.  
  112.         /**
  113.          * Correct priority
  114.          * @param int $v
  115.          * @return int
  116.            */
  117.         public function priorIt($v){
  118.                 $v = $v > 1?'1':$v;
  119.                 $v = $v < 0?'0.1':$v;
  120.                 return $v;
  121.         }
  122.  
  123.         /**
  124.          * Send message to search engine
  125.          * @param string $sm_ping
  126.          * @param string $sm_url
  127.            */
  128.         public function pingSE($sm_ping = null, $sm_url = null){
  129.                 try{
  130.                         $ping = $sm_ping.urlencode($sm_url);
  131.                         $c = curl_init();
  132.                         curl_setopt($c, CURLOPT_URL, $ping);
  133.                         curl_setopt($c, CURLOPT_HEADER, 1);
  134.                         curl_setopt($c, CURLOPT_NOBODY, 1);
  135.                         curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  136.                         curl_setopt($c, CURLOPT_FRESH_CONNECT, 1);
  137.                         if (!curl_exec($c)) {throw new Exception("Не удалось установить соединение с сервером поисковика");}
  138.                         $httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);
  139.                         echo ($httpcode == 200)?'Отправлено уведомление':'Не удалось отправить уведомление';
  140.                         $this->pingstat = ($httpcode == 200)?'done':'failed';
  141.                 }catch(Exception $x){echo $x->getMessage();}
  142. }
  143.  
  144.         /**
  145.          * SitemapGenerator destructor
  146.            */
  147.         function __destruct(){
  148.                 if($this->del){unlink($this->fsitemap);}
  149.                 $log['date'] = date("Y-m-d");
  150.                 $log['links'] = serialize($this->val);
  151.                 $log['ping'] = $this->pingstat;
  152.                 try{$this->dbh->exec("INSERT INTO n VALUES ('{$log['date']}', '{$log['links']}', '{$log['ping']}')");}
  153.                 catch(Exception $x){echo "Не могу выполнить запрос";}
  154.                 }
  155. }
  156. ?>

 

Вариант использования:

  1.  
  2. $s[0][] = 'http://zhukoff.com/archives/60';
  3. $s[0][] = '2008-06-05';
  4. $s[0][] = 'hourly';
  5. $s[0][] = '0.5';
  6.  
  7. $s[1][] = 'http://zhukoff.com/archives/59';
  8. $s[1][] = '2008-05-05';
  9. $s[1][] = '';
  10. $s[1][] = '-10';
  11.  
  12. $s[2][] = 'http://zhukoff.com/archives/53';
  13.  
  14. $s[3][] = 'http://zhukoff.com/archives/52';
  15. $s[3][] = '2008-05-04';
  16.  
  17. $ping = 'http://www.google.com/webmasters/tools/ping?sitemap=';
  18. $sitemap = 'http://www.site.ru/sitemap.xml';
  19.  
  20. $a = new SitemapGenerator();
  21. $a->addLinks($s);
  22. $a->pingSE($ping,$sitemap);
  23.  

Скачать SitemapGenerator

Полезные ссылки:

  1. комментарии (5) to “Класс для работы с Sitemaps”

  2.   BiOgr -- Jul 5, 2008

    Можно намнооого проще сделать!…


  3.   Alex -- Jul 7, 2008

    Можно есть руками, а можно ножом и вилкой.


  4.   Ivanlipeckoy -- Aug 7, 2008

    Хорошая вещь


  5.   pIZ -- Aug 11, 2008

    Вы сами это придумали? Если да, то неплохо получилось:)


  6.   Grench -- Sep 4, 2008

    Отлично мне понравилось


Комментировать