Generate Sitemap in Phalcon


Nov '14

25d ago

4

1653

1


tuananhpro
1.7k

So!! What is sitemap ?

A site map is a list of pages of a web site accessible to crawlers or users. It can be either a document in any form used as a planning tool for Web design, or a Web page that lists the pages on a Web site, typically organized in hierarchical fashion

Generate Sitemap in Phalcon

In project we will create a controller name is "SitemapController.php" with following content

    class SitemapController extends Controller
    {

        /**
         * Generate the website sitemap
         *
         */
        public function indexAction()
        {

            $response = new Response();

            $expireDate = new \DateTime();
            $expireDate->modify('+1 day');

            $response->setExpires($expireDate);

            $response->setHeader('Content-Type', "application/xml; charset=UTF-8");

            $sitemap = new \DOMDocument("1.0", "UTF-8");

            $urlset = $sitemap->createElement('urlset');
            $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
            $urlset->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');

            $baseUrl = $this->config->site->url;

            $url = $sitemap->createElement('url');
            $url->appendChild($sitemap->createElement('loc', $baseUrl));
            $url->appendChild($sitemap->createElement('changefreq', 'daily'));
            $url->appendChild($sitemap->createElement('priority', '1.0'));
            $urlset->appendChild($url);


            $posts = Posts::find(["order" => "modified_at DESC","limit"=>20]);


            $modifiedAt = new \DateTime();
            $modifiedAt->setTimezone(new \DateTimeZone('UTC'));

            foreach ($posts as $post) {

                $modifiedAt->setTimestamp($post->modified_at);

                $url = $sitemap->createElement('url');
                $href = $baseUrl . '/discussion/' . $post->id . '/' . $post->slug;
                $url->appendChild(
                    $sitemap->createElement('loc', $href)
                );

                $url->appendChild($sitemap->createElement('lastmod', $modifiedAt->format('Y-m-d\TH:i:s\Z')));
                $urlset->appendChild($url);
            }

            $sitemap->appendChild($urlset);

            $response->setContent($sitemap->saveXML());
            return $response;
        }
    }

We will explain it, In above example We have a router is sitemap and action index we get laster 20 post from database then it render via method setContent

As you can see, very easy


Nhi
5.3k

web777
74

It is slow variant. Only for small sitemaps