PHP code example of gpslab / sitemap

1. Go to this page and download the library: Download gpslab/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/ */

    

gpslab / sitemap example snippets


// URLs on your site
$urls = [
    Url::create(
        'https://example.com/', // loc
        new \DateTimeImmutable('2020-06-15 13:39:46'), // lastmod
        ChangeFrequency::always(), // changefreq
        10 // priority
    ),
    Url::create(
        'https://example.com/contacts.html',
        new \DateTimeImmutable('2020-05-26 09:28:12'),
        ChangeFrequency::monthly(),
        7
    ),
    Url::create('https://example.com/about.html'),
];

// file into which we will write a sitemap
$filename = __DIR__.'/sitemap.xml';

// configure stream
$render = new PlainTextSitemapRender();
$writer = new TempFileWriter();
$stream = new WritingStream($render, $writer, $filename);

// build sitemap.xml
$stream->open();
foreach ($urls as $url) {
    $stream->push($url);
}
$stream->close();

   $change_frequency = 'daily';
   

   $change_frequency = ChangeFrequency::DAILY;
   

   $change_frequency = ChangeFrequency::daily();
   

   $priority = '0.5';
   

   $priority = .5;
   

   $priority = 5;
   

   $priority = Priority::create(5 /* string|float|int */);
   

// URLs on your site
$urls = [
    Url::create(
        'https://example.com/english/page.html',
        new \DateTimeImmutable('2020-06-15 13:39:46'),
        ChangeFrequency::monthly(),
        7,
        [
            'de' => 'https://example.com/deutsch/page.html',
            'de-ch' => 'https://example.com/schweiz-deutsch/page.html',
            'en' => 'https://example.com/english/page.html',
            'fr' => 'https://example.fr',
            'x-default' => 'https://example.com/english/page.html',
        ]
    ),
    Url::create(
        'https://example.com/deutsch/page.html',
        new \DateTimeImmutable('2020-06-15 13:39:46'),
        ChangeFrequency::monthly(),
        7,
        [
            'de' => 'https://example.com/deutsch/page.html',
            'de-ch' => 'https://example.com/schweiz-deutsch/page.html',
            'en' => 'https://example.com/english/page.html',
            'fr' => 'https://example.fr',
            'x-default' => 'https://example.com/english/page.html',
        ]
    ),
    Url::create(
        'https://example.com/schweiz-deutsch/page.html',
        new \DateTimeImmutable('2020-06-15 13:39:46'),
        ChangeFrequency::monthly(),
        7,
        [
            'de' => 'https://example.com/deutsch/page.html',
            'de-ch' => 'https://example.com/schweiz-deutsch/page.html',
            'en' => 'https://example.com/english/page.html',
            'fr' => 'https://example.fr',
            'x-default' => 'https://example.com/english/page.html',
        ]
    ),
];

$urls = Url::createLanguageUrls(
    [
        'de' => 'https://example.com/deutsch/page.html',
        'de-ch' => 'https://example.com/schweiz-deutsch/page.html',
        'en' => 'https://example.com/english/page.html',
        'x-default' => 'https://example.com/english/page.html',
    ],
    new \DateTimeImmutable('2020-06-15 13:39:46'),
    ChangeFrequency::monthly(),
    7,
    [
        'fr' => 'https://example.fr',
    ]
);

class MySiteUrlBuilder implements UrlBuilder
{
    public function getIterator(): \Traversable
    {
        // add URLs on your site
        return new \ArrayIterator([
          Url::create(
              'https://example.com/', // loc
              new \DateTimeImmutable('2020-06-15 13:39:46'), // lastmod
              ChangeFrequency::always(), // changefreq
              10 // priority
          ),
          Url::create(
              'https://example.com/contacts.html',
              new \DateTimeImmutable('2020-05-26 09:28:12'),
              ChangeFrequency::monthly(),
              7
          ),
          Url::create(
              'https://example.com/about.html',
              new \DateTimeImmutable('2020-05-02 17:12:38'),
              ChangeFrequency::monthly(),
              7
          ),
       ]);
    }
}

class ArticlesUrlBuilder implements UrlBuilder
{
    private $pdo;

    public function __construct(\PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function getIterator(): \Traversable
    {
        $section_update_at = null;
        $sth = $this->pdo->query('SELECT id, update_at FROM article');
        $sth->execute();

        while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
            $update_at = new \DateTimeImmutable($row['update_at']);
            $section_update_at = max($section_update_at, $update_at);

            // smart URL automatically fills fields that it can
            yield Url::createSmart(
                sprintf('https://example.com/article/%d', $row['id']),
                $update_at
            );
        }

        // link to section
        if ($section_update_at !== null) {
            yield Url::createSmart('https://example.com/article/', $section_update_at);
        } else {
            yield Url::create(
                'https://example.com/article/',
                new \DateTimeImmutable('-1 day'),
                ChangeFrequency::daily(),
                9
            );
        }
    }
}

// collect a collection of builders
$builders = new MultiUrlBuilder([
    new MySiteUrlBuilder(),
    new ArticlesUrlBuilder(/* $pdo */),
]);

// file into which we will write a sitemap
$filename = __DIR__.'/sitemap.xml';

// configure stream
$render = new PlainTextSitemapRender();
$writer = new TempFileWriter();
$stream = new WritingStream($render, $writer, $filename);

// build sitemap.xml
$stream->open();
foreach ($builders as $url) {
    $stream->push($url);
}
$stream->close();

// file into which we will write a sitemap
$filename = __DIR__.'/sitemap.xml';

// configure stream
$render = new PlainTextSitemapIndexRender();
$writer = new TempFileWriter();
$stream = new WritingIndexStream($render, $writer, $filename);

// build sitemap.xml index
$stream->open();
$stream->pushSitemap(new Sitemap('https://example.com/sitemap_main.xml', new \DateTimeImmutable('-1 hour')));
$stream->pushSitemap(new Sitemap('https://example.com/sitemap_news.xml', new \DateTimeImmutable('-1 hour')));
$stream->pushSitemap(new Sitemap('https://example.com/sitemap_articles.xml', new \DateTimeImmutable('-1 hour')));
$stream->close();

// collect a collection of builders
$builders = new MultiUrlBuilder([
    new MySiteUrlBuilder(),
    new ArticlesUrlBuilder(/* $pdo */),
]);

// file into which we will write a sitemap
$index_filename = __DIR__.'/sitemap.xml';

$index_render = new PlainTextSitemapIndexRender();
$index_writer = new TempFileWriter();

// file into which we will write a sitemap part
// filename should contain a directive like "%d"
$part_filename = __DIR__.'/sitemap%d.xml';

// web path to the sitemap.xml on your site
$part_web_path = 'https://example.com/sitemap%d.xml';

$part_render = new PlainTextSitemapRender();
// separate writer for part
// it's better not to use one writer as a part writer and a index writer
// this can cause conflicts in the writer
$part_writer = new TempFileWriter();

// configure stream
$stream = new WritingSplitIndexStream(
    $index_render,
    $part_render,
    $index_writer,
    $part_writer,
    $index_filename,
    $part_filename,
    $part_web_path
);

$stream->open();

// build sitemap.xml index file and sitemap1.xml, sitemap2.xml, sitemapN.xml with URLs
foreach ($builders as $url) {
    $stream->push($url);
}

// you can add a link to a sitemap created earlier
$stream->pushSitemap(new Sitemap('https://example.com/sitemap_news.xml', new \DateTimeImmutable('-1 hour')));

$stream->close();

// file into which we will write a sitemap
$index_filename = __DIR__.'/sitemap.xml';

$index_render = new PlainTextSitemapIndexRender();
$index_writer = new TempFileWriter();

// separate writer for part
$part_writer = new TempFileWriter();
$part_render = new PlainTextSitemapRender();

$index_stream = new WritingIndexStream($index_render, $index_writer, $index_filename);

// create a stream for news

// file into which we will write a sitemap part
// filename should contain a directive like "%d"
$news_filename = __DIR__.'/sitemap_news%d.xml';
// web path to sitemap parts on your site
$news_web_path = 'https://example.com/sitemap_news%d.xml';
$news_stream = new WritingSplitStream($part_render, $part_writer, $news_filename, $news_web_path);

// similarly create a stream for articles
$articles_filename = __DIR__.'/sitemap_articles%d.xml';
$articles_web_path = 'https://example.com/sitemap_articles%d.xml';
$articles_stream = new WritingSplitStream($part_render, $part_writer, $articles_filename, $articles_web_path);

// similarly create a main stream
$main_filename = __DIR__.'/sitemap_main%d.xml';
$main_web_path = 'https://example.com/sitemap_main%d.xml';
$main_stream = new WritingSplitStream($part_render, $part_writer, $main_filename, $main_web_path);

// build sitemap.xml index
$index_stream->open();

$news_stream->open();
// build parts of a sitemap group
foreach ($news_urls as $url) {
    $news_stream->push($url);
}

// add all parts to the index
foreach ($news_stream->getSitemaps() as $sitemap) {
    $index_stream->pushSitemap($sitemap);
}

// close the stream only after adding all parts to the index
// otherwise the list of parts will be cleared
$news_stream->close();

// similarly for articles stream
$articles_stream->open();
foreach ($article_urls as $url) {
    $articles_stream->push($url);
}
foreach ($articles_stream->getSitemaps() as $sitemap) {
    $index_stream->pushSitemap($sitemap);
}
$articles_stream->close();

// similarly for main stream
$main_stream->open();
foreach ($main_urls as $url) {
    $main_stream->push($url);
}
foreach ($main_stream->getSitemaps() as $sitemap) {
    $index_stream->pushSitemap($sitemap);
}
$main_stream->close();

// finish create index
$index_stream->close();

$stream = new MultiStream(
    new LoggerStream(/* $logger */),
    new WritingSplitIndexStream(
        new PlainTextSitemapIndexRender(),
        new PlainTextSitemapRender(),
        new TempFileWriter(),
        new GzipTempFileWriter(9),
         __DIR__.'/sitemap.xml',
         __DIR__.'/sitemap%d.xml.gz',
        'https://example.com/sitemap%d.xml.gz'
    )
);

$render = new PlainTextSitemapRender();

$stream = new MultiStream(
    new LoggerStream(/* $logger */),
    new WritingStream($render, new GzipTempFileWriter(9), __DIR__.'/sitemap.xml.gz'),
    new WritingStream($render, new TempFileWriter(), __DIR__.'/sitemap.xml')
);

$render = new PlainTextSitemapRender();

$stream = new MultiStream(
    new LoggerStream(/* $logger */),
    new WritingStream($render, new TempFileWriter(), __DIR__.'/sitemap.xml'),
    new OutputStream($render)
);

// file into which we will write a sitemap
$filename = __DIR__.'/catalog/sitemap.xml';

// configure stream
$render = new PlainTextSitemapRender();
$writer = new TempFileWriter();
$wrapped_stream = new WritingStream($render, $writer, $filename);

// all URLs not started with this path will be considered invalid
$scope = 'https://example.com/catalog/';

// decorate stream
$stream = new ScopeTrackingStream($wrapped_stream, $scope);

// build sitemap.xml
$stream->open();
// this is a valid URLs
$stream->push(Url::create('https://example.com/catalog/'));
$stream->push(Url::create('https://example.com/catalog/123-my_product.html'));
$stream->push(Url::create('https://example.com/catalog/brand/'));
// using these URLs will throw exception
//$stream->push(Url::create('https://example.com/')); // parent path
//$stream->push(Url::create('https://example.com/news/')); // another path
//$stream->push(Url::create('http://example.com/catalog/')); // another scheme
//$stream->push(Url::create('https://example.com:80/catalog/')); // another port
//$stream->push(Url::create('https://example.org/catalog/')); // another domain
$stream->close();