php生成sitemap的类(class)其实很简单,但为了方便还是写成了一个类,附php生成sitemap的类文档下载以及示例说明
<?php
/***************************************
$文件名: class.sitemap.php $
$描述: php生成sitemap类$
$版本: 1.0 $
$最后修改日期: 2007/01/01 09:04:11 $
$作者: psdshow (psdshow(@)yahoo.com.cn) $
$个人站点 http://www.dayanmei.com $
****************************************/
class sitemap {
var $charset = "UTF-8";
var $s = "";
function sitemap($encoding = '') {
if(empty($encoding)){
$encoding = "UTF-8";
}
$this->s = "<?xml version=\"1.0\" encoding=\"$encoding\"?>\n";
$this->s .= "<urlset xmlns=\"http://www.google.com/schemas/sitemap/0.84\">\n";
}
/*****************
* $loc url地址 符号要转义
符号 & &
单引号 ' '
双引号 " "
大于 > >
小于 < <
* $lastmod 修改时间 W3C Datetime 可以使用YYYY-mm-dd
* $changefreq 更新频率 always hourly daily weekly monthly yearly never
* $priority 重要性 0.1-1.0之间
*******************/
function addurl($loc, $lastmod = '', $changefreq = '', $priority = '') {
$loc = htmlentities($loc,ENT_QUOTES);
$this->s .= "\t\t<url>\n\t\t\t<loc>$loc</loc>\n";
if(!empty($lastmod)){
$this->s .= "\t\t\t<lastmod>$lastmod</lastmod>\n";
}
if(!empty($changefreq)){
$this->s .= "\t\t\t<changefreq>$changefreq</changefreq>\n";
}
if(!empty($priority)){
$this->s .= "\t\t\t<priority>$priority</priority>\n";
}
$this->s .= "\t\t</url>\n\n";
}
function buildsitemap($filename = "") {
$this->s .= "\t</urlset>\n";
if(empty($filename)){
header("Content-Type: text/xml");
echo $this->s;
}else{
$this->save2file($filename);
return true;
}
}
function save2file($filename) {
$fp = @fopen($filename,"w+") or die(sprintf("建立文件1%失败",$filename));
@fwrite($fp,$this->s);
@fclose($fp);
}
}
?>
sitemap类使用示例
<?php
/***************************************
$文件名: demo.php $
$描述: 演示文件 $
$版本: 1.0 $
$最后修改日期: 2007-9-15 $
$作者: psdshow (psdshow@yahoo.com.cn) $
****************************************/
header("Content-Type: text/html; charset=utf-8");
require_once('class.sitemap.php');
$sitemapfile = 'demo.xml';
$sitemap = new sitemap();
$data = array(
array(
'loc' => 'http://www.dayanmei.com/index.php',
'lastmod' => '2007-09-15',
'changefreq' => 'daily',
'priority' => '0.9'
),
array(
'loc' => 'http://www.dayanmei.com/index.php?action=index&page=1',
'lastmod' => '2007-09-15',
'changefreq' => 'daily',
'priority' => '0.6'
)
);
foreach($data as $k=>$v) {
$sitemap->addurl($v['loc'],$v['lastmod'],$v['changefreq'],$v['priority']);
}
if($sitemap->buildsitemap($sitemapfile)){
echo '成功建立sitemap文件:<a href="'.$sitemapfile.'">'.$sitemapfile.'</a>';
}
?>
php生成sitemap 完整源文件下载
http://www.dayanmei.com/upload/sitemap_class.rar