Installation
composer require dlapps/sitemap-bundle
Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3.x):
DL\SitemapBundle\DLSitemapBundle::class => ['all' => true],
First Sitemap Definition Create a service or command to define and generate a sitemap:
use DL\SitemapBundle\Definition\Sitemap;
use DL\SitemapBundle\Definition\Resource;
$sitemap = new Sitemap();
$sitemap->addResource(new Resource('https://example.com', '2023-10-01', 0.8, 'daily'));
Generate and Output
Use the SitemapGenerator service to render the sitemap:
$generator = $container->get('dl_sitemap.generator');
$xml = $generator->generate($sitemap);
file_put_contents('public/sitemap.xml', $xml);
First Use Case Generate a basic sitemap for your homepage and key routes:
$sitemap = new Sitemap();
$sitemap->addResource(new Resource('https://example.com'));
$sitemap->addResource(new Resource('https://example.com/about'));
$sitemap->addResource(new Resource('https://example.com/contact'));
Dynamic Sitemap Generation Fetch routes dynamically from Symfony’s router and populate the sitemap:
$router = $container->get('router');
$routes = $router->getRouteCollection()->all();
foreach ($routes as $route) {
$sitemap->addResource(new Resource($router->generate($route->getName())));
}
Cron-Based Generation
Schedule a command to regenerate sitemaps nightly (e.g., via cron or Laravel’s task scheduler):
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class GenerateSitemapCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output)
{
$sitemap = new Sitemap();
// Add resources...
$generator = $this->getContainer()->get('dl_sitemap.generator');
file_put_contents('public/sitemap.xml', $generator->generate($sitemap));
$output->writeln('Sitemap generated!');
}
}
Multi-Language Sitemaps
Use the Sitemap class to create separate sitemaps for each locale:
$locales = ['en', 'fr', 'es'];
foreach ($locales as $locale) {
$sitemap = new Sitemap();
$sitemap->setLocale($locale);
// Add locale-specific resources...
$generator->generate($sitemap, "public/sitemap_$locale.xml");
}
Integration with Controllers Generate sitemaps on-demand (e.g., for API-driven sites):
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class SitemapController
{
#[Route('/sitemap.xml', name: 'sitemap')]
public function generateSitemap(Request $request)
{
$sitemap = new Sitemap();
// Add resources...
$generator = $this->get('dl_sitemap.generator');
return new Response($generator->generate($sitemap), 200, [
'Content-Type' => 'application/xml',
]);
}
}
$cache = $container->get('cache.app');
if (!$cache->has('sitemap')) {
$xml = $generator->generate($sitemap);
$cache->set('sitemap', $xml, 3600); // Cache for 1 hour
} else {
$xml = $cache->get('sitemap');
}
Resource class to add custom metadata (e.g., video sitemaps):
class VideoResource extends Resource
{
public function __construct(string $loc, string $lastmod = null, float $changefreq = 0.5, string $priority = 1.0, string $title = null, string $description = null)
{
parent::__construct($loc, $lastmod, $changefreq, $priority);
$this->title = $title;
$this->description = $description;
}
}
use Symfony\Component\Validator\Validator\ValidatorInterface;
$validator = $container->get('validator');
$errors = $validator->validate($resource->getLoc(), new UrlConstraints());
if (count($errors) === 0) {
$sitemap->addResource($resource);
}
Deprecated Symfony 3.x Usage
config/bundles.php instead of AppKernel.php). Ensure you’re using the correct registration method.config/bundles.php for Symfony 4+:
return [
// ...
DL\SitemapBundle\DLSitemapBundle::class => ['all' => true],
];
XML Output Formatting
ns namespace or incorrect root element). The bundle’s default output is minimal.$xml = str_replace('<urlset>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">', $xml);
Large Sitemaps
$resources = $sitemap->getResources();
$chunkSize = 50000;
$chunks = array_chunk($resources, $chunkSize);
foreach ($chunks as $index => $chunk) {
$chunkSitemap = new Sitemap();
foreach ($chunk as $resource) {
$chunkSitemap->addResource($resource);
}
file_put_contents("public/sitemap_$index.xml", $generator->generate($chunkSitemap));
}
Lastmod Precision
lastmod field should be in YYYY-MM-DD format. Using timestamps or incorrect formats may cause validation errors.$resource = new Resource('https://example.com', (new \DateTime())->format('Y-m-d'));
Dependency Conflicts
spatie/sitemap). Avoid installing multiple sitemap packages in the same project.Validate XML Output Use online tools like XML Validation to check the generated sitemap for errors. Common issues include:
url elements.xmlns).Check Resource Order The bundle does not enforce any order for resources. If your sitemap requires a specific order (e.g., by priority), sort the resources manually:
usort($sitemap->getResources(), function ($a, $b) {
return $b->getPriority() <=> $a->getPriority();
});
Symfony Debug Mode Enable Symfony’s debug mode to catch issues early:
APP_DEBUG=1 php bin/console dl:sitemap:generate
SitemapGenerator to add custom logic (e.g., compression, signing):
use DL\SitemapBundle\Generator\SitemapGenerator;
class CustomSitemapGenerator extends SitemapGenerator
{
public function generate(Sitemap $s
How can I help you explore Laravel packages today?