bitandblack/sitemap

通过解析整个网站创建sitemap.xml。

2.0.6 2024-03-01 11:06 UTC

This package is auto-updated.

Last update: 2024-08-30 12:12:40 UTC


README

PHP from Packagist Codacy Badge Latest Stable Version Total Downloads License

Bit&Black Sitemap

通过解析整个网站(包括所有语言版本和所有图片)创建sitemap.xml

如果发现多个语言版本,将写入多个xml文件。

安装

此库是为与Composer一起使用而制作的。通过运行$ composer require bitandblack/sitemap将其添加到您的项目中。

用法

自动生成整个网站的站点地图

设置站点地图生成如下

<?php

use BitAndBlack\Sitemap\Config\YamlConfig;
use BitAndBlack\Sitemap\SitemapCrawler;
use BitAndBlack\Sitemap\Writer\FileWriter;

$config = new YamlConfig('/path/to/config.yaml');
$writer = new FileWriter('/path/to/xml/files');

$sitemapCrawler = new SitemapCrawler(
    $config,
    $writer
);

$sitemapCrawler->createSitemap('https://crawl.me');

YamlConfig 存储一些信息,当过程需要分多步运行时需要这些信息。因此,它需要一个配置文件可能存储的路径。

FileWriter 存储xml文件,因此它需要知道这些文件的文件夹。

createSitemap() 开始爬取。如果达到时间限制,过程将停止并将状态存储在配置文件中。如果您再次调用createSitemap(),它将继续过程。这对于可能需要很长时间才能爬取的大型网站很有帮助。

选项

页面限制

设置页面限制,当达到定义的页面数时停止爬虫

<?php

$sitemapCrawler->setCrawlingLimit(500);

爬取单个页面

您可以通过使用PageCrawler类来爬取单个页面。它将生成包含页面标题、正文以及有关语言、链接和媒体的一些信息的对象。

<?php

use BitAndBlack\Sitemap\PageCrawler;

$pageCrawler = new PageCrawler('https://www.bitandblack.com/de.html');
$page = $pageCrawler->getPage();

手动生成sitemap.xml

您也可以自己创建sitemap.xml

<?php

use BitAndBlack\Sitemap\Collection;
use BitAndBlack\Sitemap\Config\YamlConfig;
use BitAndBlack\Sitemap\Page;
use BitAndBlack\Sitemap\SitemapXML;

$collection = new Collection(
    new YamlConfig()
);

/**
 * The page doesn't need to exist.
 */
$page = new Page('https://example.org');

$sitemapXML = new SitemapXML($collection, [$page]);

file_put_contents(
    'sitemap.xml',
    $sitemapXML->getSitemap()->saveXML()
);

可用的爬取器

默认情况下,Bit&Black Sitemap库使用Symfony Http Client进行请求。

根据您的需求,您可以使用不同的爬取器。目前支持的有

AutoPageCrawler 将通过自身检测可用的爬取器。

但是,您可以设置PageCrawler 使用特定的爬取器,例如

<?php

use BitAndBlack\Sitemap\PageCrawler;
use BitAndBlack\Sitemap\PageCrawler\ReactCrawler;

$pageCrawler = new PageCrawler();
$pageCrawler->setPageCrawler(new ReactCrawler());

帮助

如果您有任何问题,请随时通过hello@bitandblack.com联系我们。

有关Bit&Black的更多信息,请访问www.bitandblack.com