Класс для работы с Sitemaps
16 June 2008 – 19:56Выкладываю самописный класс для работы с Sitemaps. Класс умеет генерировать (SimpleXML) новую sitemap или добавлять в уже существующую позиции из массива ссылок и необязательных параметров (lastmod, changefreq, priority). Умеет уведомлять поисковик о сгенерированной карте (CURL). Пишет лог в БД (через PDO). Позже добавлю еще пару полезных методов. Если что непонятно - спрашивайте. Также приветствуются поправки и рекомендации.
Класс:
-
<?php
-
/**
-
* Sitemap Generator Class
-
*
-
* @author Alex Zhukoff
-
* @license http://creativecommons.org/licenses/by-sa/3.0/ (Creative Commons BY-SA)
-
* @version 1.0
-
* @link http://zhukoff.com
-
*/
-
-
class SitemapGenerator {
-
-
private $fsitemap = 'sitemap.xml';
-
public $schema = 'http://www.google.com/schemas/sitemap/0.84';
-
public $pingstat = 'failed';
-
private $dbh = null;
-
private $val = null;
-
private $del = null;
-
-
/**
-
* SitemapGenerator constructor
-
* @param string $fsitemap
-
* @param string $schema
-
*/
-
function __construct($fsitemap = null, $schema = null){
-
$this->schema = !$schema ? $this->schema : $schema;
-
$this->cPDO('localhost','mysql','db','root','');
-
}
-
-
/**
-
* DB connection
-
* @param string $h host
-
* @param string $s dns
-
* @param string $db database
-
* @param string $u user
-
* @param string $p pass
-
* @access private
-
*/
-
private function cPDO($h = '127.0.0.1',$s = 'mysql',$db = 'db',$u = 'root',$p = ''){
-
$this->dbh = new PDO($s.':dbname='.$db.';host='.$h, $u, $p);
-
}
-
-
/**
-
* DB connection
-
* @access private
-
*/
-
private function createSM(){
-
file_put_contents($this->fsitemap,$this->wrap());
-
$this->del = 1;
-
}
-
-
/**
-
* Sitemap file header
-
* @access private
-
*/
-
private function wrap(){
-
return '<?xml version="1.0" encoding="UTF-8"?>'."\n".
-
'<urlset xmlns="'.$this->schema.'">'."\n".
-
'</urlset>';
-
}
-
-
/**
-
* "Add links" wrapper
-
* @param mixed $val Could be either an array or an string
-
*/
-
public function addLinks($val = null){
-
try{$this->pAdd($val);}
-
}
-
-
/**
-
* Add links
-
* @param mixed $val Could be either an array or an string
-
* @access private
-
*/
-
private function pAdd($val){
-
elseif(@$val[0][0] != null){$this->val = $val;}
-
else{throw new Exception("Не передано ни одной ссылки");}
-
-
$load = simplexml_load_file($this->fsitemap);
-
foreach($this->val as $v){
-
$tm = $load->addChild('url');
-
if($this->chkAdd('lnk',$v[0]))$tm->addChild('loc', $v[0]);
-
if($this->chkAdd('lmd',$v[1]))$tm->addChild('lastmod', $v[1]);
-
if($this->chkAdd('chf',$v[2]))$tm->addChild('changefreq', $v[2]);
-
if($v[3] = $this->chkAdd('pri',$v[3]))$tm->addChild('priority', $v[3]);
-
}
-
$tmp = $load->asXML();
-
file_put_contents($this->fsitemap, $tmp);
-
$this->del = null;
-
}
-
-
/**
-
* Check links
-
* @param string $t
-
* @param mixed $v Could be either an string or an int
-
* @return mixed Could be an string or an int or null
-
*/
-
public function chkAdd($t,$v){
-
switch ($t){
-
case 'lmd':return ($v == '')?null:$v;
-
case 'pri':return ($v == '')?null:$this->priorIt($v);
-
}
-
}
-
-
/**
-
* Correct priority
-
* @param int $v
-
* @return int
-
*/
-
public function priorIt($v){
-
$v = $v > 1?'1':$v;
-
$v = $v < 0?'0.1':$v;
-
return $v;
-
}
-
-
/**
-
* Send message to search engine
-
* @param string $sm_ping
-
* @param string $sm_url
-
*/
-
public function pingSE($sm_ping = null, $sm_url = null){
-
try{
-
$c = curl_init();
-
curl_setopt($c, CURLOPT_URL, $ping);
-
curl_setopt($c, CURLOPT_HEADER, 1);
-
curl_setopt($c, CURLOPT_NOBODY, 1);
-
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
-
curl_setopt($c, CURLOPT_FRESH_CONNECT, 1);
-
if (!curl_exec($c)) {throw new Exception("Не удалось установить соединение с сервером поисковика");}
-
$httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);
-
$this->pingstat = ($httpcode == 200)?'done':'failed';
-
}
-
-
/**
-
* SitemapGenerator destructor
-
*/
-
function __destruct(){
-
$log['ping'] = $this->pingstat;
-
try{$this->dbh->exec("INSERT INTO n VALUES ('{$log['date']}', '{$log['links']}', '{$log['ping']}')");}
-
}
-
}
-
?>
Вариант использования:
-
-
$s[0][] = 'http://zhukoff.com/archives/60';
-
$s[0][] = '2008-06-05';
-
$s[0][] = 'hourly';
-
$s[0][] = '0.5';
-
-
$s[1][] = 'http://zhukoff.com/archives/59';
-
$s[1][] = '2008-05-05';
-
$s[1][] = '';
-
$s[1][] = '-10';
-
-
$s[2][] = 'http://zhukoff.com/archives/53';
-
-
$s[3][] = 'http://zhukoff.com/archives/52';
-
$s[3][] = '2008-05-04';
-
-
$ping = 'http://www.google.com/webmasters/tools/ping?sitemap=';
-
$sitemap = 'http://www.site.ru/sitemap.xml';
-
-
$a = new SitemapGenerator();
-
$a->addLinks($s);
-
$a->pingSE($ping,$sitemap);
-
Полезные ссылки:

комментарии (3) to “Класс для работы с Sitemaps”
BiOgr -- Jul 5, 2008
Можно намнооого проще сделать!…
Alex -- Jul 7, 2008
Можно есть руками, а можно ножом и вилкой.
Ivanlipeckoy -- Aug 7, 2008
Хорошая вещь