PHP code example of sergeybruhin / xml-sitemap

1. Go to this page and download the library: Download sergeybruhin/xml-sitemap library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sergeybruhin / xml-sitemap example snippets




namespace App\Console\Commands;

use App\Models\Page;
use Illuminate\Console\Command;
use SergeyBruhin\XmlSitemap\Dto\XmlSitemapImage;
use SergeyBruhin\XmlSitemap\Dto\XmlSitemapSitemap;
use SergeyBruhin\XmlSitemap\Dto\XmlSitemapUrl;
use SergeyBruhin\XmlSitemap\Facades\XmlSitemap;

class GenerateSitemapCommand extends Command
{
    protected $signature = 'generate:sitemap';

    protected $description = 'Generate sitemap';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle(): int
    {
        $sitemapIndex = XmlSitemap::createIndex();
        $sitemapIndex->addSitemap($this->createPagesSitemap());

        XmlSitemap::storeIndex($sitemapIndex);
        foreach ($sitemapIndex->sitemaps as $sitemap) {
            XmlSitemap::storeSitemap($sitemap);
        }

        return 1;

    }

    private function createPagesSitemap(): XmlSitemapSitemap
    {
        $sitemap = XmlSitemap::createSitemap('pages_sitemap.xml');

        Page::each(function (Page $page) use ($sitemap) {
            $url = new XmlSitemapUrl(route('page', $page->slug), 0.8);
            $url->setLastModificationDate($page->updated_at);
            $url->setFrequency(XmlSitemapUrl::WEEKLY);
            $url->addAlternate(route('page', $page->slug) . '/en', 'en');
            $url->addImage((new XmlSitemapImage('https://some/image/url.png')));

            $sitemap->addUrl($url);
        });
        return $sitemap;
    }
}


  protected function schedule(Schedule $schedule): void
    {
        $schedule->command('generate:sitemap')->hourly();
    }