netglue / sitemap-builder
一个简单的XML站点地图生成工具
Requires
- php: >=7.3
- ext-xmlwriter: *
- laminas/laminas-uri: ^2.7
Requires (Dev)
- doctrine/coding-standard: ^8.1
- phpunit/phpunit: ^9.4
This package is auto-updated.
Last update: 2024-09-17 05:52:37 UTC
README
为什么?
制作XML站点地图很简单,而且市面上有很多工具,但这些工具往往只关注将XML持久化到磁盘。如果你在几台服务器上运行应用程序,磁盘就是个大麻烦。
我想找一个只生成XML字符串的工具,这样我就可以轻松地将它用于缓存,或者序列化到AWS或Google云等文件系统。
安装
按照常规方式使用composer进行安装…
composer require netglue/sitemap-builder
此库需要xml writer扩展,并且至少需要PHP 7.1
测试
覆盖率目前为100%,只需切换到项目目录并…
$ composer install
$ vendor/bin/phpunit
使用方法
单个独立站点地图
如果你不需要站点地图索引文件,即你永远不会超过50,000个URL,那么以下内容应该足够
use Netglue\Sitemap\Sitemap;
$sitemap = new Sitemap('some-file.xml', 'http://base-host-and-scheme.com');
$sitemap->addUri('/somewhere');
$xml = (string) $sitemap; // or $sitemap->toXmlString()
// Now do whatever with your xml…
Sitemap::addUri()
的签名是
Sitemap::addUri(
\Laminas\Uri\UriInterface|string $uri,
?\DateTimeInterface $lastMod = null,
?string $changeFreq = null,
?float $priority = null
) : void;
具有索引的多个站点地图
当每个站点地图的最大位置计数达到时,将自动生成新的站点地图。每个站点地图将被命名为 sitemap-{index}.xml
,其中 {index}
从零开始
use Netglue\Sitemap\SitemapIndex;
use Netglue\Sitemap\Sitemap;
$index = new SitemapIndex('http://baseurl.host');
// Optionally limit sitemap size (Default is 50k)
$index->setMaxEntriesPerSitemap(10);
// Add a shed load of relative, or absolute URIs
$index->addUri('/someplace');
// ...
// Retrieve the sitemaps and do something with them:
foreach ($index->getSitemaps() as $sitemap) {
/** @var Sitemap $sitemap */
$xml = (string) $sitemap;
$filename = $sitemap->getName(); // i.e 'sitemap-0.xml'
}
// Do somthing with the Index XML
$indexXml = (string) $index;
写入磁盘
我想如果有人使用这个库,他们可能希望将站点地图写入磁盘,因此它还包含一个简单的写入类
use Netglue\Sitemap\Writer\FileWriter;
use Netglue\Sitemap\SitemapIndex;
$writer = new FileWriter('/path/to/disk/location');
$writer->writeIndex($index);
上述代码将把站点地图索引和找到的所有站点地图写入指定的目录。你也可以提供文件名,而不是默认的 sitemap-index.xml
。如果你只处理单个站点地图,那么这个就足够了
use Netglue\Sitemap\Writer\FileWriter;
use Netglue\Sitemap\Sitemap;
$writer = new FileWriter('/path/to/disk/location');
$writer->writeSitemap($sitemap, 'my-sitemap.xml');
文件名是可选的,默认为 $sitemap->getName()
异常
会抛出一致的异常,这些异常都实现了 Netglue\Sitemap\Exception\ExceptionInterface
。例如,更改频率必须根据模式有效。优先级必须在0和1之间的浮点数等。
许可协议
此库是MIT许可。随意使用,但如果有问题不要怪任何人
反馈和贡献…
…受到欢迎。请为任何修复或功能请求添加测试。
关于
我们希望这对你有所帮助,无论怎样我们都感激您的反馈 :)。