evert / sitemap-php
轻量级库,用于生成Google sitemap XML文件
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2020-01-24 14:59:25 UTC
README
快速且轻量级的类,用于生成Google sitemap XML文件和sitemap文件索引。使用PHP编写,并使用XMLWriter扩展(libxml xmlWriter API的包装器)来创建XML文件。XMLWriter扩展在PHP 5 >= 5.1.2中默认启用。如果您有超过50,000个URL,它会将项目分割到单独的文件中。(在基准测试中,1,000,000个URL在8秒内生成)
这是原始版本的轻微修改版。Sitemap类现在添加到了'SitemapPHP'命名空间,并添加了composer文档。
要求
- PHP 5.1.2及以上版本
步骤
安装
Composer
运行以下命令通过Composer包含此包:
composer require evert/sitemap-php
包含
将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。
维护者
此包由Evert Pot、David Oti、Osman Ungur、Mike Lay、Userlond、Philipp Scheit和您维护。
许可证
此包受MIT许可证许可。