priyank2005/sitemap

此包最新版本(1.0.0)没有可用的许可信息。

1.0.0 2014-06-26 16:40 UTC

This package is not auto-updated.

Last update: 2024-09-24 03:04:33 UTC


README

对于90年代的人,我保留这个仓库与5.2兼容。如果您需要PSR-0和Composer兼容版本,请访问Evert Pot维护的分支

什么是sitemap-php ?

这是一个用于生成Google站点地图XML文件和站点地图文件索引的快速、轻量级类。使用PHP编写并使用XMLWriter扩展(libxml xmlWriter API的包装器)来创建XML文件。XMLWriter扩展在PHP 5 >= 5.1.2中默认启用。如果您有超过50000个URL,它将项目拆分为单独的文件。 (在基准测试中,1,000,000个URL在8秒内生成)

如何使用

将Sitemap.php文件包含到您的PHP文档中,并使用您的基域调用Sitemap类。

include 'Sitemap.php';
$sitemap = new Sitemap('http://example.com');	

现在,我们需要定义保存XML文件的路径。这可以是相对路径如xmls或绝对路径/path/to/your/folder,并且必须是一个可写文件夹。默认情况下,它使用与您的脚本相同的文件夹。

$sitemap->setPath('xmls/');

生成的XML文件名默认为sitemap-*.xml,您可以使用setFilename方法自定义文件名的前缀。

$sitemap->setFilename('customsitemap');

我们将使用addItem方法添加站点地图URL。在这个方法中,只需要第一个参数(位置)。

$sitemap->addItem('/', '1.0', 'daily', 'Today');
$sitemap->addItem('/about', '0.8', 'monthly', 'Jun 25');
$sitemap->addItem('/contact', '0.6', 'yearly', '14-12-2009');
$sitemap->addItem('/otherpage');

使用方法链。

$sitemap->addItem('/projects', '0.8')->addItem('/somepage')->addItem('/hiddenpage', '0.4', 'yearly', '01-01-2011')->addItem('/rss');

从SQL结果或任何其他内容。

$query = Doctrine_Query::create()
				->select('p.created_at, p.slug')
				->from('Posts p')
				->orderBy('p.id DESC')
				->useResultCache(true);
$posts =  $query->fetchArray(array(), Doctrine_Core::HYDRATE_ARRAY);
foreach ($posts as $post) {
    $sitemap->addItem('/post/' . $post['slug'], '0.6', 'weekly', $post['created_at']);
}

如果您需要更改站点地图实例的域,可以通过setDomain方法覆盖它。

$sitemap->setDomain('http://blog.example.com');

最后,我们为站点地图文件创建索引。此方法还将关闭最新生成的XML文件的标签。

$sitemap->createSitemapIndex('http://example.com/sitemap/', 'Today');

当您运行脚本时,它将在给定路径生成并保存XML文件。

sitemap-0.xml

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <url>
  <loc>http://example.com/</loc>
  <priority>1.0</priority>
  <changefreq>daily</changefreq>
  <lastmod>2011-04-07</lastmod>
 </url>
 <url>
  <loc>http://example.com/about</loc>
  <priority>0.8</priority>
  <changefreq>monthly</changefreq>
  <lastmod>2011-06-25</lastmod>
 </url>
 <url>
  <loc>http://example.com/contact</loc>
  <priority>0.6</priority>
  <changefreq>yearly</changefreq>
  <lastmod>2009-12-14</lastmod>
 </url>
 <url>
  <loc>http://example.com/otherpage</loc>
  <priority>0.5</priority>
 </url>
</urlset>

sitemap-index.xml

<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <sitemap>
  <loc>http://example.com/sitemap/sitemap-0.xml</loc>
  <lastmod>2011-04-07</lastmod>
 </sitemap>
</sitemapindex>

您需要提交sitemap-index.xml到Google Sitemaps。