用户
 找回密码
 入住 CI 中国社区
搜索
查看: 7871|回复: 9
收起左侧

生成Sitemap(网站地图)程序代码怎样写

[复制链接]
发表于 2011-1-25 16:39:14 | 显示全部楼层 |阅读模式
本人是初学者,做了个网站需要Sitemap.xml给蜘蛛,但不知道这段代码怎样写。请教各位大侠了!
发表于 2011-1-25 17:35:22 | 显示全部楼层
 楼主| 发表于 2011-1-25 18:17:03 | 显示全部楼层
回复 2# jeongee

jeongee妹:

我需要的是网站自有此功能,例如:每天自动更新检查本站的Sitemap.xml。这就省去了到http://www.xml-sitemaps.com/里去手动制作。

现需要的功能就是自动生成Sitemap.xml的功能。
 楼主| 发表于 2011-1-26 03:56:04 | 显示全部楼层
本帖最后由 linggano 于 2011-1-26 04:02 编辑

刚好在网上找到,用来参考。


查看源代码打印帮助
001 /**  

002  * @category   class  

003  * @package    SitemapGenerator  

004  * @author     Paweł Antczak <pawel@antczak.org>  

005  * @translate  10V | www.smartwei.com  

006  * @copyright  2009 Paweł Antczak  

007  * @license    http://www.gnu.org/licenses/gpl.html  GPL V 2.0  

008  * @version    1.2.0  

009  * @see        http://www.sitemaps.org/protocol.php  

010  * @see        http://en.wikipedia.org/wiki/Sitemaps  

011  * @see        http://en.wikipedia.org/wiki/Sitemap_index  

012  */

013 class SitemapGenerator {  

014     /**  

015      * sitemap的名字  

016      * @var string  

017      * @access public  

018      */

019     public $sitemapFileName = "sitemap.xml";  

020     /**  

021      * sitemap索引的名字  

022      * @var string  

023      * @access public  

024      */

025   

026     public $sitemapIndexFileName = "sitemap-index.xml";  

027     /**  

028      * robots文件的名字  

029      * @var string  

030      * @access public  

031      */

032     public $robotsFileName = "robots.txt";  

033     /**  

034      * 每一个sitemap文件包含的连接数  

035      * 每个sitemap文件包含连接数最好不要 50,000.  

036      * sitemap文件的大小最好不要超过10MB,如果网站的链接很长的话,请减少页面包含链接数  

037      * @var int  

038      * @access public  

039      */

040     public $maxURLsPerSitemap = 50000;  

041     /**  

042      * 如果该变量设置为true, 会生成两个sitemap文件,后缀名分别是.xml和.xml.gz 而且会被添加到robots.txt文件中.  

043      * 同时.gz文件会被提交给搜索引擎。  

044      * 如果每页包含的连接数大于50,000,则这个字段将被忽略,除了sitemap索引文件之外,其他sitemap文件都会被压缩  

045      * @var bool  

046      * @access public  

047      */

048     public $createGZipFile = false;  

049     /**  

050      * 网站的url  

051      * 脚本向搜索引擎提交sitemap时会用到这个变量  

052      * @var string  

053      * @access private  

054      */

055     private $baseURL;  

056     /**  

057      * 相关脚本的路径  

058      * 当你想把sitemap和robots文件放在不同的路径时,设置这个变量。  

059      * @var string  

060      * @access private  

061      */

062     private $basePath;  

063     /**  

064      * 这个类的版本号  

065      * @var string  

066      * @access private  

067      */

068     private $classVersion = "1.2.0";  

069     /**  

070      * 搜索引擎的URL  

071      * @var array of strings  

072      * @access private  

073      */

074     private $searchEngines = array(  

075         array("http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=USERID&url=",  

076         "http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap="),  

077         "http://www.google.com/webmasters/tools/ping?sitemap=",  

078         "http://submissions.ask.com/ping?sitemap=",  

079         "http://www.bing.com/webmaster/ping.aspx?siteMap="

080     );  

081     /**  

082      * url数组  

083      * @var array of strings  

084      * @access private  

085      */

086     private $urls;  

087     /**  

088      * sitemap的数组  

089      * @var array of strings  

090      * @access private  

091      */

092   

093     private $sitemaps;  

094     /**  

095      * sitemap索引的数组  

096      * @var array of strings  

097      * @access private  

098      */

099   

100     private $sitemapIndex;  

101      /**  

102      * 当前sitemap的全路径  

103      * @var string  

104      * @access private  

105      */

106     private $sitemapFullURL;  

107   

108     /**  

109      * 构造函数  

110      * @param string $baseURL 你网站的URL, 以 / 结尾.  

111      * @param string|null $basePath sitemap和robots文件存储的相对路径.  

112      */

113     public function __construct($baseURL, $basePath = "") {  

114         $this->baseURL = $baseURL;  

115         $this->basePath = $basePath;  

116     }  

117     /**  

118      * 使用这个方法可以同时添加多个url  

119      * 每个链接有4个参数可以设置  

120      * @param array of arrays of strings $urlsArray  

121      */

122     public function addUrls($urlsArray) {  

123         if (!is_array($urlsArray))  

124             throw new InvalidArgumentException('参数$aURLs需要时数组');  

125         foreach ($urlsArray as $url) {  

126             $this->addUrl(isset ($url[0]) ? $url[0] : null,  

127                 isset ($url[1]) ? $url[1] : null,  

128                 isset ($url[2]) ? $url[2] : null,  

129                 isset ($url[3]) ? $url[3] : null);  

130         }  

131     }  

132     /**  

133      * 使用这个方法每次添加一个连接到sitemap中  

134      * @param string $url URL  

135      * @param string $lastModified 当被修改时,使用ISO 8601  

136      * @param string $changeFrequency 搜索引擎抓取信息的频率  

137      * @param string $priority 你网站中连接的权重  

138      * @see http://en.wikipedia.org/wiki/ISO_8601  

139      * @see http://php.net/manual/en/function.date.php  

140      */

141     public function addUrl($url, $lastModified = null, $changeFrequency = null, $priority = null) {  

142         if ($url == null)  

143             throw new InvalidArgumentException("URL 是必填项.");  

144         $urlLenght = extension_loaded('mbstring') ? mb_strlen($url) : strlen($url);  

145         if ($urlLenght > 2048)  

146             throw new InvalidArgumentException("URL的长度不能超过2048。  

147                                                 请注意,见此url长度需要使用mb_string扩展.  

148                                                 请确定你的服务器已经打开了这个模块");  

149         $tmp = array();  

150         $tmp['loc'] = $url;  

151         if (isset($lastModified)) $tmp['lastmod'] = $lastModified;  

152         if (isset($changeFrequency)) $tmp['changefreq'] = $changeFrequency;  

153         if (isset($priority)) $tmp['priority'] = $priority;  

154         $this->urls[] = $tmp;  

155     }  

156     /**  

157      * 在内存中创建sitemap.  

158      */

159     public function createSitemap() {  

160         if (!isset($this->urls))  

161             throw new BadMethodCallException("请先加载addUrl或者addUrls方法.");  

162         if ($this->maxURLsPerSitemap > 50000)  

163             throw new InvalidArgumentException("每个sitemap中的链接不能超过50,000个");  

164   

165         $generatorInfo = '<!-- generator="SimpleSitemapGenerator/'.$this->classVersion.'" -->  

166                           <!-- sitemap-generator-url="http://www.antczak.org"

167                           sitemap-generator-version="'.$this->classVersion.'" -->  

168                           <!-- generated-on="'.date('c').'" -->';  

169         $sitemapHeader = '<?xml version="1.0" encoding="UTF-8"?>'.$generatorInfo.'  

170                             <urlset  

171                                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

172                                 xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9  

173                                 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"  

174                                 xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">  

175                          </urlset>';  

176         $sitemapIndexHeader = '<?xml version="1.0" encoding="UTF-8"?>'.$generatorInfo.'  

177                                 <sitemapindex  

178                                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

179                                     xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9  

180                                     http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd"  

181                                     xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">  

182                               </sitemapindex>';  

183         foreach(array_chunk($this->urls,$this->maxURLsPerSitemap) as $sitemap) {  

184             $xml = new SimpleXMLElement($sitemapHeader);  

185             foreach($sitemap as $url) {  

186                 $row = $xml->addChild('url');  

187                 $row->addChild('loc',htmlspecialchars($url['loc'],ENT_QUOTES,'UTF-8'));  

188                 if (isset($url['lastmod'])) $row->addChild('lastmod', $url['lastmod']);  

189                 if (isset($url['changefreq'])) $row->addChild('changefreq',$url['changefreq']);  

190                 if (isset($url['priority'])) $row->addChild('priority',$url['priority']);  

191             }  

192             if (strlen($xml->asXML()) > 10485760)  

193                 throw new LengthException("sitemap文件的大小不能超过10MB (10,485,760),  

194                     please decrease maxURLsPerSitemap variable.");  

195             $this->sitemaps[] = $xml->asXML();  

196   

197         }  

198         if (sizeof($this->sitemaps) > 1000)  

199             throw new LengthException("sitemap索引文件最多可以包含1000条索引.");  

200         if (sizeof($this->sitemaps) > 1) {  

201             for($i=0; $i<sizeof($this->sitemaps); $i++) {  

202                 $this->sitemaps[$i] = array(  

203                     str_replace(".xml", ($i+1).".xml.gz", $this->sitemapFileName),  

204                     $this->sitemaps[$i]  

205                 );  

206             }  

207             $xml = new SimpleXMLElement($sitemapIndexHeader);  

208             foreach($this->sitemaps as $sitemap) {  

209                 $row = $xml->addChild('sitemap');  

210                 $row->addChild('loc',$this->baseURL.htmlentities($sitemap[0]));  

211                 $row->addChild('lastmod', date('c'));  

212             }  

213             $this->sitemapFullURL = $this->baseURL.$this->sitemapIndexFileName;  

214             $this->sitemapIndex = array(  

215                 $this->sitemapIndexFileName,  

216                 $xml->asXML());  

217         }  

218         else {  

219             if ($this->createGZipFile)  

220                 $this->sitemapFullURL = $this->baseURL.$this->sitemapFileName.".gz";  

221             else

222                 $this->sitemapFullURL = $this->baseURL.$this->sitemapFileName;  

223             $this->sitemaps[0] = array(  

224                 $this->sitemapFileName,  

225                 $this->sitemaps[0]);  

226         }  

227     }  

228     /**  

229      * 如果你不想生成sitemap文件,指向用其中的内容,这个返回的数组就包含了对应的信息.  

230      * @return 字符串数组  

231      * @access public  

232      */

233     public function toArray() {  

234         if (isset($this->sitemapIndex))  

235             return array_merge(array($this->sitemapIndex),$this->sitemaps);  

236         else

237             return $this->sitemaps;  

238     }  

239     /**  

240      * 写sitemap文件  

241      * @access public  

242      */

243     public function writeSitemap() {  

244         if (!isset($this->sitemaps))  

245             throw new BadMethodCallException("请先加载createSitemap方法.");  

246         if (isset($this->sitemapIndex)) {  

247             $this->_writeFile($this->sitemapIndex[1], $this->basePath, $this->sitemapIndex[0]);  

248             foreach($this->sitemaps as $sitemap) {  

249                 $this->_writeGZipFile($sitemap[1], $this->basePath, $sitemap[0]);  

250             }  

251         }  

252         else {  

253             $this->_writeFile($this->sitemaps[0][1], $this->basePath, $this->sitemaps[0][0]);  

254             if ($this->createGZipFile)  

255                 $this->_writeGZipFile($this->sitemaps[0][1], $this->basePath, $this->sitemaps[0][0].".gz");  

256         }  

257     }  

258     /**  

259      * 如果robots.txt文件存在,更新该文件,将新添加的信息写入其中  

260      * 如果robots.txt文件不存在,则创建该文件,写入刚添加的信息  

261      * @access public  

262      */

263     public function updateRobots() {  

264         if (!isset($this->sitemaps))  

265             throw new BadMethodCallException("请先加载createSitemap方法");  

266         $sampleRobotsFile = "User-agent: *\nAllow: /";  

267         if (file_exists($this->basePath.$this->robotsFileName)) {  

268             $robotsFile = explode("\n", file_get_contents($this->basePath.$this->robotsFileName));  

269             $robotsFileContent = "";  

270             foreach($robotsFile as $key=>$value) {  

271                 if(substr($value, 0, <IMG class=wp-smiley alt=8) src="http://www.smartwei.com/wp-includes/images/smilies/icon_cool.gif"> == 'Sitemap:') unset($robotsFile[$key]);  

272                 else $robotsFileContent .= $value."\n";  

273             }  

274             $robotsFileContent .= "Sitemap: $this->sitemapFullURL";  

275             if ($this->createGZipFile && !isset($this->sitemapIndex))  

276                 $robotsFileContent .= "\nSitemap: ".$this->sitemapFullURL.".gz";  

277             file_put_contents($this->basePath.$this->robotsFileName,$robotsFileContent);  

278         }  

279         else {  

280             $sampleRobotsFile = $sampleRobotsFile."\n\nSitemap: ".$this->sitemapFullURL;  

281             if ($this->createGZipFile && !isset($this->sitemapIndex))  

282                 $sampleRobotsFile .= "\nSitemap: ".$this->sitemapFullURL.".gz";  

283             file_put_contents($this->basePath.$this->robotsFileName, $sampleRobotsFile);  

284         }  

285     }  

286     /**  

287      * 将新生成的sitemap提交给搜索引擎,包括:Google, Ask, Bing and Yahoo。  

288      * 如果你没有填写yahooid,yahoo也会被通知。  

289      * 但是每天最多提交一次,重复提交yahoo会拒绝接受信息  

290      * @param string $yahooAppId 你网站的Yahoo Id  

291      * @return 以数组形式返回每个搜索引擎的消息  

292      * @access public  

293      */

294     public function submitSitemap($yahooAppId = null) {  

295         if (!isset($this->sitemaps))  

296             throw new BadMethodCallException("To submit sitemap, call createSitemap function first.");  

297         if (!extension_loaded('curl'))  

298             throw new BadMethodCallException("cURL library is needed to do submission.");  

299         $searchEngines = $this->searchEngines;  

300         $searchEngines[0] = isset($yahooAppId) ? str_replace("USERID", $yahooAppId, $searchEngines[0][0]) : $searchEngines[0][1];  

301         $result = array();  

302         for($i=0;$i<sizeof($searchEngines);$i++) {  

303             $submitSite = curl_init($searchEngines[$i].htmlspecialchars($this->sitemapFullURL,ENT_QUOTES,'UTF-8'));  

304             curl_setopt($submitSite, CURLOPT_RETURNTRANSFER, true);  

305             $responseContent = curl_exec($submitSite);  

306             $response = curl_getinfo($submitSite);  

307             $submitSiteShort = array_reverse(explode(".",parse_url($searchEngines[$i], PHP_URL_HOST)));  

308             $result[] = array("site"=>$submitSiteShort[1].".".$submitSiteShort[0],  

309                 "fullsite"=>$searchEngines[$i].htmlspecialchars($this->sitemapFullURL, ENT_QUOTES,'UTF-8'),  

310                 "http_code"=>$response['http_code'],  

311                 "message"=>str_replace("\n", " ", strip_tags($responseContent)));  

312         }  

313         return $result;  

314     }  

315     /**  

316      * 保存文件  

317      * @param string $content  

318      * @param string $filePath  

319      * @param string $fileName  

320      * @return bool  

321      * @access private  

322      */

323     private function _writeFile($content, $filePath, $fileName) {  

324         $file = fopen($filePath.$fileName, 'w');  

325         fwrite($file, $content);  

326         return fclose($file);  

327     }  

328     /**  

329      * 保存 GZipped文件.  

330      * @param string $content  

331      * @param string $filePath  

332      * @param string $fileName  

333      * @return bool  

334      * @access private  

335      */

336     private function _writeGZipFile($content, $filePath, $fileName) {  

337         $file = gzopen($filePath.$fileName, 'w');  

338         gzwrite($file, $content);  

339         return gzclose($file);  

340     }  

341 }

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

查看源代码打印帮助01 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  

02 <html>  

03     <head>  

04         <title></title>  

05         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  

06     </head>  

07     <body>  

08         <?php  

09             include 'SitemapGenerator.php';  

10             $sitemap = new SitemapGenerator("http://www.smartwei.com/");  

11   

12             //添加url,如果你的url是通过程序生成的,这里就可以循环添加了。  

13             $sitemap->addUrl("http://www.smartwei.com/",  date('c'),  'daily',  '1');  

14             $sitemap->addUrl("http://www.smartwei.com/speed-up-firefox.html", date('c'),  'daily',    '0.5');  

15             $sitemap->addUrl("http://www.smartwei.com/php-form-check-class.html", date('c'),  'daily');  

16             $sitemap->addUrl("http://www.smartwei.com/32-userful-web-design-blogs.html", date('c'));  

17   

18             //创建sitemap  

19             $sitemap->createSitemap();  

20   

21             //生成sitemap文件  

22             $sitemap->writeSitemap();  

23   

24             //更新robots.txt文件  

25             $sitemap->updateRobots();  

26   

27             //提交sitemap到搜索引擎  

28             $sitemap->submitSitemap();  

29         ?>  

30     </body>  

31 </html>


源自:http://www.smartwei.com/php-sitemap-generator-class.html
发表于 2011-1-26 10:44:15 | 显示全部楼层
朋友,有这个必要吗?
发表于 2011-1-26 10:45:13 | 显示全部楼层
不要为了seo去seo,
你看腾讯有吗?
http://www.qq.com/Sitemap.xml
 楼主| 发表于 2011-1-27 14:16:15 | 显示全部楼层
本帖最后由 linggano 于 2012-1-19 00:53 编辑

{:soso_e100:}
发表于 2011-1-28 01:09:34 | 显示全部楼层
我也是初学者,这个东西是做什么的 我现在还不知道呢
发表于 2011-3-5 21:11:53 | 显示全部楼层
回复 2# jeongee 这个网站好啊
发表于 2011-3-6 10:37:23 | 显示全部楼层
结合数据库逐个写入sitemap.xml

或看http://codeigniter.com/wiki/Sitemap
www.smartweb.cn

本版积分规则