Easy sitemaps with separate index files

Submitted by nlogachev - 10 years ago

Uses "thepixeldeveloper/sitemap": "dev-master" in composer.json to create a better organised sitemap structure via multiple "files" (routes).

/* in routes.php */

//Setup the sitemap index file
Route::get('sitemap.xml', function() {

    //ISO 8601
    $now = date_create('now')->format('c');

    $collection = new \Sitemap\Collection;

    //Create a new index entry for another
    $map = new \Sitemap\Sitemap\SitemapEntry;
	$map->setLocation(URL::to('sitemap-content.xml'));
	$map->setLastMod($now);
    //Add this entry to this sitemap's set of entries
	$collection->addSitemap($map);
    
    //Repeat as many times as you want for multiple "files" to create a
    //better-organised sitemap structure.
    
    //Set the sitemap generator to an index format
	$collection->setFormatter(new \Sitemap\Formatter\XML\SitemapIndex);

    //Render the sitemap
	return $collection->output();

});

//Setup individual sitemaps linked from the index
Route::get('sitemap-content.xml', function() {

    //ISO 8601
	$now = date_create('now')->format('c');

    $collection = new \Sitemap\Collection;

    //For example, let's get all of our news articles
	$news = Article::wherePublished(1)->orderBy('published_date','desc')->get();

    //Go through each one, creating a new sitemap entry
    foreach ($news as $article) {

        $map = new \Sitemap\Sitemap\SitemapEntry;
        $map->setLocation(URL::to('news/'.$article->id));
        $map->setLastMod($article->updated_at->format('c'));
        $map->setChangeFreq('weekly');

        //Add this entry to this sitemap's set of entries
        $collection->addSitemap($map);

	}

    //Set the sitemap generator to a standard sitemap url set
    $collection->setFormatter(new \Sitemap\Formatter\XML\URLSet);

    //Render the sitemap XML
	return $collection->output();

});