myqaa/laravel-sitemap

轻松创建和生成网站地图

dev-main 2023-01-15 14:19 UTC

This package is auto-updated.

Last update: 2024-09-15 18:10:53 UTC


README

Latest Version on Packagist Software License Test Status Code Style Status Total Downloads

此包可以生成网站地图,而无需您手动添加URL。这是通过爬取您的整个网站实现的。

use Spatie\Sitemap\SitemapGenerator;

SitemapGenerator::create('https://example.com')->writeToFile($path);

您也可以手动创建您的网站地图

use Carbon\Carbon;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

Sitemap::create()

    ->add(Url::create('/home')
        ->setLastModificationDate(Carbon::yesterday())
        ->setChangeFrequency(Url::CHANGE_FREQUENCY_YEARLY)
        ->setPriority(0.1))

   ->add(...)

   ->writeToFile($path);

或者,您可以两者兼得,先生成网站地图,然后添加更多链接

SitemapGenerator::create('https://example.com')
   ->getSitemap()
   ->add(Url::create('/extra-page')
        ->setLastModificationDate(Carbon::yesterday())
        ->setChangeFrequency(Url::CHANGE_FREQUENCY_YEARLY)
        ->setPriority(0.1))

    ->add(...)

    ->writeToFile($path);

您还可以控制网站地图的最大深度

SitemapGenerator::create('https://example.com')
    ->configureCrawler(function (Crawler $crawler) {
        $crawler->setMaximumDepth(3);
    })
    ->writeToFile($path);

生成器具有在每个页面执行JavaScript的能力 (见链接),因此由JavaScript注入DOM的链接也将被爬取。

您还可以使用您的可用文件系统磁盘之一将网站地图写入。

SitemapGenerator::create('https://example.com')->getSitemap()->writeToDisk('public', 'sitemap.xml');

支持我们

通过观看我们的付费视频课程了解如何创建此类包

Laravel Package training

我们投入了大量资源来创建 最好的开源包。您可以通过 购买我们的付费产品之一 来支持我们。

我们非常感谢您从家乡寄来明信片,说明您正在使用我们哪些包。您可以在 我们的联系页面 上找到我们的地址。我们将在 我们的虚拟明信片墙上 发布所有收到的明信片。

安装

首先,通过composer安装此包

composer require spatie/laravel-sitemap

包将自动注册自己。

如果您想自动和频繁地更新您的网站地图,您需要执行 一些额外步骤

配置

您可以通过发布配置来覆盖爬虫的默认选项。首先发布配置

php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider" --tag=config

这会将默认配置复制到 config/sitemap.php,在那里您可以编辑它。

use GuzzleHttp\RequestOptions;
use Spatie\Sitemap\Crawler\Profile;

return [

    /*
     * These options will be passed to GuzzleHttp\Client when it is created.
     * For in-depth information on all options see the Guzzle docs:
     *
     * http://docs.guzzlephp.org/en/stable/request-options.html
     */
    'guzzle_options' => [

        /*
         * Whether or not cookies are used in a request.
         */
        RequestOptions::COOKIES => true,

        /*
         * The number of seconds to wait while trying to connect to a server.
         * Use 0 to wait indefinitely.
         */
        RequestOptions::CONNECT_TIMEOUT => 10,

        /*
         * The timeout of the request in seconds. Use 0 to wait indefinitely.
         */
        RequestOptions::TIMEOUT => 10,

        /*
         * Describes the redirect behavior of a request.
         */
        RequestOptions::ALLOW_REDIRECTS => false,
    ],
    
    /*
     * The sitemap generator can execute JavaScript on each page so it will
     * discover links that are generated by your JS scripts. This feature
     * is powered by headless Chrome.
     */
    'execute_javascript' => false,
    
    /*
     * The package will make an educated guess as to where Google Chrome is installed. 
     * You can also manually pass it's location here.
     */
    'chrome_binary_path' => '',

    /*
     * The sitemap generator uses a CrawlProfile implementation to determine
     * which urls should be crawled for the sitemap.
     */
    'crawl_profile' => Profile::class,
    
];

使用

生成网站地图

最简单的方法是爬取给定的域名并生成包含所有找到的链接的网站地图。网站地图的目标应由 $path 指定。

SitemapGenerator::create('https://example.com')->writeToFile($path);

生成的网站地图看起来类似于以下内容

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://example.com</loc>
        <lastmod>2016-01-01T00:00:00+00:00</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    <url>
        <loc>https://example.com/page</loc>
        <lastmod>2016-01-01T00:00:00+00:00</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>

    ...
</urlset>

定制网站地图生成器

定义自定义爬取配置文件

您可以通过实现 Spatie\Crawler\CrawlProfile 接口并自定义 shouldCrawl() 方法来创建自定义爬取配置文件,以全面控制哪些URL/域名/子域名应该被爬取

use Spatie\Crawler\CrawlProfile;
use Psr\Http\Message\UriInterface;

class CustomCrawlProfile extends CrawlProfile
{
    public function shouldCrawl(UriInterface $url): bool
    {
        if ($url->getHost() !== 'localhost') {
            return false;
        }
        
        return $url->getPath() === '/';
    }
}

并在 config/sitemap.php 中注册您的 CustomCrawlProfile::class

return [
    ...
    /*
     * The sitemap generator uses a CrawlProfile implementation to determine
     * which urls should be crawled for the sitemap.
     */
    'crawl_profile' => CustomCrawlProfile::class,
    
];

更改属性

要更改联系页面的 lastmodchangefreqpriority 属性

use Carbon\Carbon;
use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;

SitemapGenerator::create('https://example.com')
   ->hasCrawled(function (Url $url) {
       if ($url->segment(1) === 'contact') {
           $url->setPriority(0.9)
               ->setLastModificationDate(Carbon::create('2016', '1', '1'));
       }

       return $url;
   })
   ->writeToFile($sitemapPath);

省略一些链接

如果您不希望爬取的链接出现在网站地图中,只需在传递给 hasCrawled 的可调用函数中不返回它即可。

use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;

SitemapGenerator::create('https://example.com')
   ->hasCrawled(function (Url $url) {
       if ($url->segment(1) === 'contact') {
           return;
       }

       return $url;
   })
   ->writeToFile($sitemapPath);

防止爬虫爬取某些页面

您还可以通过传递一个 callableshouldCrawl 来指示底层爬虫不要爬取某些页面。

注意: shouldCrawl 仅与默认爬取 Profile 或实现 shouldCrawlCallback 方法的自定义爬取配置文件一起工作。

use Spatie\Sitemap\SitemapGenerator;
use Psr\Http\Message\UriInterface;

SitemapGenerator::create('https://example.com')
   ->shouldCrawl(function (UriInterface $url) {
       // All pages will be crawled, except the contact page.
       // Links present on the contact page won't be added to the
       // sitemap unless they are present on a crawlable page.
       
       return strpos($url->getPath(), '/contact') === false;
   })
   ->writeToFile($sitemapPath);

配置爬虫

爬虫本身可以被 配置 来执行一些不同的事情。

您可以为网站地图生成器配置所使用的爬虫,例如:忽略机器人检查;如下所示。

SitemapGenerator::create('https://:4020')
    ->configureCrawler(function (Crawler $crawler) {
        $crawler->ignoreRobots();
    })
    ->writeToFile($file);

限制爬取页面的数量

您可以通过调用 setMaximumCrawlCount 来限制爬取页面的数量。

use Spatie\Sitemap\SitemapGenerator;

SitemapGenerator::create('https://example.com')
    ->setMaximumCrawlCount(500) // only the 500 first pages will be crawled
    ...

执行 JavaScript

网站地图生成器可以在每个页面上执行 JavaScript,以便发现由您的 JavaScript 脚本生成的链接。您可以通过在配置文件中将 execute_javascript 设置为 true 来启用此功能。

在底层,使用 无头 Chrome 来执行 JavaScript。以下是如何在您的系统上安装它的提示:安装指南

该包将对您的系统上 Chrome 的安装位置做出合理的猜测。您也可以手动将 Chrome 可执行文件的位置传递给 executeJavaScript()

手动添加链接

您可以将链接手动添加到网站地图中。

use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;

SitemapGenerator::create('https://example.com')
    ->getSitemap()
    // here we add one extra link, but you can add as many as you'd like
    ->add(Url::create('/extra-page')->setPriority(0.5))
    ->writeToFile($sitemapPath);

为链接添加替代内容

多语言网站可能有同一页面的几个替代版本(每个语言一个)。根据之前的示例,添加替代内容的操作可以如下进行:

use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;

SitemapGenerator::create('https://example.com')
    ->getSitemap()
    // here we add one extra link, but you can add as many as you'd like
    ->add(Url::create('/extra-page')->setPriority(0.5)->addAlternate('/extra-pagina', 'nl'))
    ->writeToFile($sitemapPath);

注意 addAlternate 函数,它接受替代 URL 和它所属的本地化。

手动创建网站地图

您也可以完全手动创建网站地图。

use Carbon\Carbon;

Sitemap::create()
   ->add('/page1')
   ->add('/page2')
   ->add(Url::create('/page3')->setLastModificationDate(Carbon::create('2016', '1', '1')))
   ->writeToFile($sitemapPath);

创建网站地图索引

您可以创建网站地图索引。

use Spatie\Sitemap\SitemapIndex;

SitemapIndex::create()
    ->add('/pages_sitemap.xml')
    ->add('/posts_sitemap.xml')
    ->writeToFile($sitemapIndexPath);

您可以将一个 Spatie\Sitemap\Tags\Sitemap 对象传递过去,手动设置 lastModificationDate 属性。

use Spatie\Sitemap\SitemapIndex;
use Spatie\Sitemap\Tags\Sitemap;

SitemapIndex::create()
    ->add('/pages_sitemap.xml')
    ->add(Sitemap::create('/posts_sitemap.xml')
        ->setLastModificationDate(Carbon::yesterday()))
    ->writeToFile($sitemapIndexPath);

生成的网站地图索引将类似于以下内容

<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <sitemap>
      <loc>http://www.example.com/pages_sitemap.xml</loc>
      <lastmod>2016-01-01T00:00:00+00:00</lastmod>
   </sitemap>
   <sitemap>
      <loc>http://www.example.com/posts_sitemap.xml</loc>
      <lastmod>2015-12-31T00:00:00+00:00</lastmod>
   </sitemap>
</sitemapindex>

创建带有后续网站地图的网站地图索引

您可以通过调用 maxTagsPerSitemap 方法来生成只包含指定数量标签的网站地图。

use Spatie\Sitemap\SitemapGenerator;

SitemapGenerator::create('https://example.com')
    ->maxTagsPerSitemap(20000)
    ->writeToFile(public_path('sitemap.xml'));

频繁生成网站地图

您的网站可能需要不时进行更新。为了使您的网站地图反映这些更改,您可以定期运行生成器。最简单的方法是利用 Laravel 的默认调度功能。

您可以设置一个类似于以下示例的 artisan 命令:

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Spatie\Sitemap\SitemapGenerator;

class GenerateSitemap extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $signature = 'sitemap:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate the sitemap.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // modify this to your own needs
        SitemapGenerator::create(config('app.url'))
            ->writeToFile(public_path('sitemap.xml'));
    }
}

该命令应该在控制台内核中进行调度。

// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    ...
    $schedule->command('sitemap:generate')->daily();
    ...
}

变更日志

有关最近更改的详细信息,请参阅 变更日志

测试

首先在单独的终端会话中启动测试服务器

cd tests/server
./start_server.sh

服务器运行时,您可以执行测试

$ composer test

贡献

有关详细信息,请参阅 贡献指南

安全

如果您发现任何与安全相关的问题,请通过电子邮件 freek@spatie.be 而不是使用问题跟踪器。

鸣谢

支持我们

Spatie 是一家位于比利时安特卫普的网页设计公司。您可以在我们的网站上找到所有开源项目的概述:我们的网站

您的业务是否依赖于我们的贡献?在 Patreon 上与我们取得联系并支持我们。所有承诺都将专门用于维护和新酷炫的功能。

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件