svityaschuk / sitemap-php-2
生成Google sitemap XML文件的轻量级库
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-23 13:09:54 UTC
README
用于生成Google sitemap XML文件和sitemap文件索引的快速轻量级类。使用PHP编写,并使用XMLWriter扩展(libxml xmlWriter API的包装器)来创建XML文件。XMLWriter扩展在PHP 5 >= 5.1.2中默认启用。如果您有超过50000个URL,它将项目分割到单独的文件中。(在基准测试中,1,000,000个URL在8秒内生成)
这是原始版本的略微修改版。现在Sitemap类已添加到'SitemapPHP'命名空间,并添加了composer文档。
如何使用
将Sitemap.php文件包含到您的PHP文档中,并使用您的基域名调用Sitemap类。
include 'src/SitemapPHP/Sitemap.php';
use SitemapPHP\Sitemap;
$sitemap = new Sitemap('http://example.com');
现在,我们需要定义保存XML文件的路径。这可以是相对路径如xmls
或绝对路径/path/to/your/folder
,并且必须是一个可写文件夹。默认情况下,它使用与您的脚本相同的文件夹。
$sitemap->setPath('xmls/');
生成的XML文件名默认为sitemap-*.xml
,您可以使用setFilename
方法自定义文件名的前缀。
$sitemap->setFilename('customsitemap');
我们将使用addItem
方法添加sitemap 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']);
}
如果您需要更改sitemap实例的域名,可以通过setDomain
方法重写它。
$sitemap->setDomain('http://blog.example.com');
最后,我们为sitemap文件创建索引。此方法还会关闭最新生成的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。