How to create dynamic sitemap xml in CakePHP
2Answer
I want to share how create dynamic sitemap if you have build a dynamic website using framework cakePHP. This is might helpful for SEO where we want to every link in our website could be indexed by Google.
In this tutorial, I will show step by step how to generate sitemap.xml dynamically. Assumed that we have a controller lets say the name is News.
Step 1. Create action in the controller
In this step we need action for handle request our sitemap. On the controller put code like bellow.
public function sitemap(){ $this->layout='ajax'; $this->RequestHandler->respondAs('xml'); $listNews = $this->News->find('all',array('conditions'=>array('publish'=>1),'order'=> array('News.modified'=>'Desc'))); $this->set(compact('listNews')); }
I through variable $listNews to render all link News that will be shown in sitemap.xml. This depends on the dynamic linkwhat we want to show in sitemap.xml
Step 2. Create View based on action sitemap
On structure MVC as default we need create sitemap.ctp. On this file we will show content of sitemap.xml. This bellow are code for sitemap.ctp
<?php App::uses('CakeTime', 'Utility'); ?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc><?php echo $this->Html->url('/',true); ?></loc> <changefreq>weekly</changefreq> </url> <?php foreach ($listNews as $list): ?> <url> <loc><?php echo $this->Html->url(array('controller' => 'news', 'action' => 'detail',$list['News']['id']),true); ?></loc> <lastmod><?php echo $this->Time->toAtom($list['News']['modified']); ?></lastmod> <changefreq>weekly</changefreq> </url> <?php endforeach; ?> </urlset>
Step 3. Set config routes.php
This is last step for configure path our sitemap will be appear like www.yourdomain.com/sitemap.xml. Add this bellow code after line connect / (if there)
Router::connect('/sitemap.xml', array('controller' => 'news', 'action' => 'sitemap'));
After that open www.yourdomain.com/sitemap.xml if it works we can submit this sitemap to Google Webmaster tool.
- answered 8 years ago
- B Butts
Here's a quick'n'dirty example for you to play with and adjust to your needs:
In your controller:
public $components = array('RequestHandler');
public function sitemap()
{
Configure::write('debug', 0);
$articles = $this->Article->getSitemapInformation();
$this->set(compact('articles'));
$this->RequestHandler->respondAs('xml');
}
Your "Article" model:
public function getSitemapInformation()
{
return $this->find('all', array(/* your query here */));
}
View:
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($articles as $article): ?>
<url>
<loc><?php echo Router::url(/* generate the URLs here */); ?></loc>
<lastmod><?php echo $time->toAtom(/* last update time here */); ?></lastmod>
<changefreq>weekly</changefreq>
</url>
<?php endforeach; ?>
</urlset>
- answered 8 years ago
- B Butts
Your Answer