这篇文章,给大家介绍一个php网站地图生成类

做网站的朋友们都有过这样的经历,在一个新站刚刚开始运营时,最希望的就是百度、google这样的搜索引擎来索引自己的页面,恨不得让蜘蛛不停地爬,赶快把自己新添加的页面索引进去。

加速搜索引擎的收录方法有很多,比如在一些人气较高的地方,找与自己网站相关的板块,发一些推广文章;或者与其他站长交换一下连接,增加页面的外部链接;最基本的也是每个站长都要做的事情就是生成自己的Sitemap,提交给各大搜索引擎。

今天就和大家分享一个php网站地图生成类,希望对大家的互联网生活有所帮助。

/*** @category class* @package SitemapGenerator* @author Paweł Antczak <pawel@antczak.org>* @translate 10V | www.smartwei.com* @copyright 2009 Paweł Antczak* @license http://www.gnu.org/licenses/gpl.html GPL V 2.0* @version 1.2.0* @see http://www.sitemaps.org/protocol.php* @see http://en.wikipedia.org/wiki/Sitemaps* @see http://en.wikipedia.org/wiki/Sitemap_index*/class SitemapGenerator {/*** sitemap的名字* @var string* @access public*/public $sitemapFileName = "sitemap.xml";/*** sitemap索引的名字* @var string* @access public*/public $sitemapIndexFileName = "sitemap-index.xml";/*** robots文件的名字* @var string* @access public*/public $robotsFileName = "robots.txt";/*** 每一个sitemap文件包含的连接数* 每个sitemap文件包含连接数最好不要 50,000.* sitemap文件的大小最好不要超过10MB,如果网站的链接很长的话,请减少页面包含链接数* @var int* @access public*/public $maxURLsPerSitemap = 50000;/*** 如果该变量设置为true, 会生成两个sitemap文件,后缀名分别是.xml和.xml.gz 而且会被添加到robots.txt文件中.* 同时.gz文件会被提交给搜索引擎。* 如果每页包含的连接数大于50,000,则这个字段将被忽略,除了sitemap索引文件之外,其他sitemap文件都会被压缩* @var bool* @access public*/public $createGZipFile = false;/*** 网站的url* 脚本向搜索引擎提交sitemap时会用到这个变量* @var string* @access private*/private $baseURL;/*** 相关脚本的路径* 当你想把sitemap和robots文件放在不同的路径时,设置这个变量。* @var string* @access private*/private $basePath;/*** 这个类的版本号* @var string* @access private*/private $classVersion = "1.2.0";/*** 搜索引擎的URL* @var array of strings* @access private*/private $searchEngines = array(array("http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=USERID&url=","http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap="),"http://www.google.com/webmasters/tools/ping?sitemap=","http://submissions.ask.com/ping?sitemap=","http://www.bing.com/webmaster/ping.aspx?siteMap=");/*** url数组* @var array of strings* @access private*/private $urls;/*** sitemap的数组* @var array of strings* @access private*/private $sitemaps;/*** sitemap索引的数组* @var array of strings* @access private*/private $sitemapIndex;/*** 当前sitemap的全路径* @var string* @access private*/private $sitemapFullURL;/*** 构造函数* @param string $baseURL 你网站的URL, 以 / 结尾.* @param string|null $basePath sitemap和robots文件存储的相对路径.*/public function __construct($baseURL, $basePath = "") {$this->baseURL = $baseURL;$this->basePath = $basePath;}/*** 使用这个方法可以同时添加多个url* 每个链接有4个参数可以设置* @param array of arrays of strings $urlsArray*/public function addUrls($urlsArray) {if (!is_array($urlsArray))throw new InvalidArgumentException('参数$aURLs需要时数组');foreach ($urlsArray as $url) {$this->addUrl(isset ($url[0]) ? $url[0] : null,isset ($url[1]) ? $url[1] : null,isset ($url[2]) ? $url[2] : null,isset ($url[3]) ? $url[3] : null);}}/*** 使用这个方法每次添加一个连接到sitemap中* @param string $url URL* @param string $lastModified 当被修改时,使用ISO 8601* @param string $changeFrequency 搜索引擎抓取信息的频率* @param string $priority 你网站中连接的权重* @see http://en.wikipedia.org/wiki/ISO_8601* @see http://php.net/manual/en/function.date.php*/public function addUrl($url, $lastModified = null, $changeFrequency = null, $priority = null) {if ($url == null)throw new InvalidArgumentException("URL 是必填项.");$urlLenght = extension_loaded('mbstring') ? mb_strlen($url) : strlen($url);if ($urlLenght > 2048)throw new InvalidArgumentException("URL的长度不能超过2048。请注意,见此url长度需要使用mb_string扩展.请确定你的服务器已经打开了这个模块");$tmp = array();$tmp['loc'] = $url;if (isset($lastModified)) $tmp['lastmod'] = $lastModified;if (isset($changeFrequency)) $tmp['changefreq'] = $changeFrequency;if (isset($priority)) $tmp['priority'] = $priority;$this->urls[] = $tmp;}/*** 在内存中创建sitemap.*/public function createSitemap() {if (!isset($this->urls))throw new BadMethodCallException("请先加载addUrl或者addUrls方法.");if ($this->maxURLsPerSitemap > 50000)throw new InvalidArgumentException("每个sitemap中的链接不能超过50,000个");$generatorInfo = '<!-- generator="SimpleSitemapGenerator/'.$this->classVersion.'" --><!-- sitemap-generator-url="http://www.antczak.org"sitemap-generator-version="'.$this->classVersion.'" --><!-- generated-on="'.date('c').'" -->';$sitemapHeader = '<?xml version="1.0" encoding="UTF-8"?>'.$generatorInfo.'<urlsetxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>';$sitemapIndexHeader = '<?xml version="1.0" encoding="UTF-8"?>'.$generatorInfo.'<sitemapindexxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd"xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></sitemapindex>';foreach(array_chunk($this->urls,$this->maxURLsPerSitemap) as $sitemap) {$xml = new SimpleXMLElement($sitemapHeader);foreach($sitemap as $url) {$row = $xml->addChild('url');$row->addChild('loc',htmlspecialchars($url['loc'],ENT_QUOTES,'UTF-8'));if (isset($url['lastmod'])) $row->addChild('lastmod', $url['lastmod']);if (isset($url['changefreq'])) $row->addChild('changefreq',$url['changefreq']);if (isset($url['priority'])) $row->addChild('priority',$url['priority']);}if (strlen($xml->asXML()) > 10485760)throw new LengthException("sitemap文件的大小不能超过10MB (10,485,760),please decrease maxURLsPerSitemap variable.");$this->sitemaps[] = $xml->asXML();}if (sizeof($this->sitemaps) > 1000)throw new LengthException("sitemap索引文件最多可以包含1000条索引.");if (sizeof($this->sitemaps) > 1) {for($i=0; $i<sizeof($this->sitemaps); $i++) {$this->sitemaps[$i] = array(str_replace(".xml", ($i+1).".xml.gz", $this->sitemapFileName),$this->sitemaps[$i]);}$xml = new SimpleXMLElement($sitemapIndexHeader);foreach($this->sitemaps as $sitemap) {$row = $xml->addChild('sitemap');$row->addChild('loc',$this->baseURL.htmlentities($sitemap[0]));$row->addChild('lastmod', date('c'));}$this->sitemapFullURL = $this->baseURL.$this->sitemapIndexFileName;$this->sitemapIndex = array($this->sitemapIndexFileName,$xml->asXML());}else {if ($this->createGZipFile)$this->sitemapFullURL = $this->baseURL.$this->sitemapFileName.".gz";else$this->sitemapFullURL = $this->baseURL.$this->sitemapFileName;$this->sitemaps[0] = array($this->sitemapFileName,$this->sitemaps[0]);}}/*** 如果你不想生成sitemap文件,指向用其中的内容,这个返回的数组就包含了对应的信息.* @return 字符串数组* @access public*/public function toArray() {if (isset($this->sitemapIndex))return array_merge(array($this->sitemapIndex),$this->sitemaps);elsereturn $this->sitemaps;}/*** 写sitemap文件* @access public*/public function writeSitemap() {if (!isset($this->sitemaps))throw new BadMethodCallException("请先加载createSitemap方法.");if (isset($this->sitemapIndex)) {$this->_writeFile($this->sitemapIndex[1], $this->basePath, $this->sitemapIndex[0]);foreach($this->sitemaps as $sitemap) {$this->_writeGZipFile($sitemap[1], $this->basePath, $sitemap[0]);}}else {$this->_writeFile($this->sitemaps[0][1], $this->basePath, $this->sitemaps[0][0]);if ($this->createGZipFile)$this->_writeGZipFile($this->sitemaps[0][1], $this->basePath, $this->sitemaps[0][0].".gz");}}/*** 如果robots.txt文件存在,更新该文件,将新添加的信息写入其中* 如果robots.txt文件不存在,则创建该文件,写入刚添加的信息* @access public*/public function updateRobots() {if (!isset($this->sitemaps))throw new BadMethodCallException("请先加载createSitemap方法");$sampleRobotsFile = "User-agent: *\nAllow: /";if (file_exists($this->basePath.$this->robotsFileName)) {$robotsFile = explode("\n", file_get_contents($this->basePath.$this->robotsFileName));$robotsFileContent = "";foreach($robotsFile as $key=>$value) {if(substr($value, 0, 8) == 'Sitemap:') unset($robotsFile[$key]);else $robotsFileContent .= $value."\n";}$robotsFileContent .= "Sitemap: $this->sitemapFullURL";if ($this->createGZipFile && !isset($this->sitemapIndex))$robotsFileContent .= "\nSitemap: ".$this->sitemapFullURL.".gz";file_put_contents($this->basePath.$this->robotsFileName,$robotsFileContent);}else {$sampleRobotsFile = $sampleRobotsFile."\n\nSitemap: ".$this->sitemapFullURL;if ($this->createGZipFile && !isset($this->sitemapIndex))$sampleRobotsFile .= "\nSitemap: ".$this->sitemapFullURL.".gz";file_put_contents($this->basePath.$this->robotsFileName, $sampleRobotsFile);}}/*** 将新生成的sitemap提交给搜索引擎,包括:Google, Ask, Bing and Yahoo。* 如果你没有填写yahooid,yahoo也会被通知。* 但是每天最多提交一次,重复提交yahoo会拒绝接受信息* @param string $yahooAppId 你网站的Yahoo Id* @return 以数组形式返回每个搜索引擎的消息* @access public*/public function submitSitemap($yahooAppId = null) {if (!isset($this->sitemaps))throw new BadMethodCallException("To submit sitemap, call createSitemap function first.");if (!extension_loaded('curl'))throw new BadMethodCallException("cURL library is needed to do submission.");$searchEngines = $this->searchEngines;$searchEngines[0] = isset($yahooAppId) ? str_replace("USERID", $yahooAppId, $searchEngines[0][0]) : $searchEngines[0][1];$result = array();for($i=0;$i<sizeof($searchEngines);$i++) {$submitSite = curl_init($searchEngines[$i].htmlspecialchars($this->sitemapFullURL,ENT_QUOTES,'UTF-8'));curl_setopt($submitSite, CURLOPT_RETURNTRANSFER, true);$responseContent = curl_exec($submitSite);$response = curl_getinfo($submitSite);$submitSiteShort = array_reverse(explode(".",parse_url($searchEngines[$i], PHP_URL_HOST)));$result[] = array("site"=>$submitSiteShort[1].".".$submitSiteShort[0],"fullsite"=>$searchEngines[$i].htmlspecialchars($this->sitemapFullURL, ENT_QUOTES,'UTF-8'),"http_code"=>$response['http_code'],"message"=>str_replace("\n", " ", strip_tags($responseContent)));}return $result;}/*** 保存文件* @param string $content* @param string $filePath* @param string $fileName* @return bool* @access private*/private function _writeFile($content, $filePath, $fileName) {$file = fopen($filePath.$fileName, 'w');fwrite($file, $content);return fclose($file);}/*** 保存 GZipped文件.* @param string $content* @param string $filePath* @param string $fileName* @return bool* @access private*/private function _writeGZipFile($content, $filePath, $fileName) {$file = gzopen($filePath.$fileName, 'w');gzwrite($file, $content);return gzclose($file);}}

给大家一个例子参考一下,首先创建一个文件,名字叫做sitemap-generator.php, 内容如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title></title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body><?phpinclude 'SitemapGenerator.php';$sitemap = new SitemapGenerator("http://www.smartwei.com/");//添加url,如果你的url是通过程序生成的,这里就可以循环添加了。$sitemap->addUrl("http://www.smartwei.com/", date('c'), 'daily', '1');$sitemap->addUrl("http://www.smartwei.com/speed-up-firefox.html", date('c'), 'daily', '0.5');$sitemap->addUrl("http://www.smartwei.com/php-form-check-class.html", date('c'), 'daily');$sitemap->addUrl("http://www.smartwei.com/32-userful-web-design-blogs.html", date('c'));//创建sitemap$sitemap->createSitemap();//生成sitemap文件$sitemap->writeSitemap();//更新robots.txt文件$sitemap->updateRobots();//提交sitemap到搜索引擎$sitemap->submitSitemap();?></body></html>

如果你的网站每天新增页面数量较少,基本上每天执行一次就可以了。如果比较多的话,可以根据你的需求创建定时执行的任务。这样,就可以使你想各大搜索引擎提交的sitemap始终是最新的了。

PHP网站地图生成类相关推荐

  1. 分享一个网站地图生成工具

    为什么分享这个网站地图生成工具?因为除了懂开发的大牛们,还有很多想我们这样的普通SEO工作者,使用现成的工具更符合现实. 最近发现的这个网站地图生成工具生成的页面比较全面,没有做更多的限制,也许还在内 ...

  2. 推荐一个网站地图生成工具

    开WEB视界sitemap网站地图生成工具(http://sitemap.webkk.net),按照页面说明,很方便的就生成了全站的网站地图. 生成地图之后,你需要做的是,向百度或者其他搜索引擎提交你 ...

  3. 织梦dedecms网站地图生成在根目录的开发教程

    前言 网站地图,对于做seo来说是非常重要的,可是织梦系统生成的网站地图默认不是生成在网站根目录的,这样不利于蜘蛛的发现,从不利于seo优化.岛主整理了一下让织梦网站地图生成在根目录的开发教程. 开发 ...

  4. https网站地图生成工具

    众所周知,网站地图制作是SEO工作当中比不可少的一部分.在HTTPS成为主流趋势的今天,发现之前一直使用的网站地图制作工具抓取不了HTTPS网站. 接下来推荐一款HTTPS网站地图制作工具亲测可用的, ...

  5. Sitemap网站地图生成工具(适用于所有网站)

    前言: Sitemap网站地图生成工具是为数不多免费的.无限制的生成sitemap的XML.HTML.TXT版本的工具之一. 现在市面上的大部分网站CMS都支持自动生成Sitemap网站地图,但是部分 ...

  6. php自动生成网站地图txt,织梦网站地图生成插件+发布文章后自动生成地图

    织梦网站地图生成插件,可同时在网站根目录生成5种地图文件. 下载地址(根据自己网站编码选择安装) 百度网盘 提取码: 3bjg 安装好后的生成菜单在模块一栏里面 如果你想把生成网站地图这个菜单放在生成 ...

  7. 织梦网站地图生成插件下载

    网站地图不但可以让浏览用户一览网站框架,对于搜索引擎对网站的收录和抓取同样起着相当重要的作用.今天跟大家分享一款好用的织梦织梦网站地图生成插件. 用过织梦的朋友应当都知道,织梦自带的网站地图只包含了顶 ...

  8. 织梦根目录生成php文件,织梦dedecms内置网站地图生成根目录路径

    织梦dedecms 后台生成下面"更新网站地图"以及"更新RSS文件"默认保存在data目录下, 之前我帮客户搭建的织梦dedecms站点在robots.txt ...

  9. ios 点生成线路 百度地图_网站地图全面解析

    网站地图相信大家都不陌生,但对于一些刚刚接触seo的小伙伴来说可能会有些疑惑.这段时间我也时常听到有学员说网站地图怎么去制作分析,搞得也是非常的头痛,现在就来带大家全面透析网站地图吧. 一.什么是网站 ...

最新文章

  1. Spring Boot实现定时任务的动态增删启停
  2. 2021未来科学大奖揭晓:SARS病原发现者、上海交大张杰教授等4人获得百万奖金...
  3. 使用NeMo快速入门NLP、实现机器翻译任务,英伟达专家实战讲解,内附代码
  4. notepad++ php开发环境,Notepad++可以结合命令行来搭建各种编程环境
  5. 《研磨设计模式》chap16 模板方法模式
  6. 嘿!不用太过于担心的单点故障
  7. u-boot中添加自定义命令
  8. android 设置folder类型,正确配置你的 Android 项目
  9. sql server限制查询条数_18. Django 2.1.7 查询集 QuerySet
  10. 因代码不规范,码农枪击4名同事,一人情况危急
  11. shell while循环
  12. 2022天勤数据结构
  13. oa项目经验描述_项目执行简历中的项目经验怎么写
  14. tomcat5下get请求中文乱码
  15. 深圳台电:联合国的“沟通”之道
  16. windows安装mongodb 时msi文件打不开解决方案
  17. 0基础女生学网络安全合适吗
  18. 关于SIGHUP信号的讨论
  19. error LNK2005: _DllMain@12 已经在 MSVCRTD.lib(dllmain.obj) 中定义
  20. C++:应用有限差分法求解 稳平流扩散方程 v*ux-k*uxx=0 in 一个空间维度,具有恒定的速度 v 和扩散系数 k(附完整源码)

热门文章

  1. mysql gbk排序规则_Mysql 字符集及排序规则
  2. 雪浪数制CEO王峰:关于雪浪制造大脑的三大拷问 | 2018雪浪大会
  3. C语言题目代码总结解析
  4. 问题:我的xmindpro从桌面打开就弹窗发生错误
  5. 期货开户公司行情资讯及时高效
  6. vs2017\vs2019 VGG19处理cifar-10数据集的TensorFlow实现
  7. 苹果手机怎样录屏 如何录制手机内容
  8. 图形2d,3d加速简介
  9. vue,的M、V、VM分别代表什么
  10. Java处理Excel文件工具包-easyexcel使用详解