Shahid Najam Afridi
Shahid Najam Afridi

Reputation: 139

how to create sitemap using zend framework?

I want create sitemap. I use zend framwork. I dont know much about sitemap. any one knows how to create sitemap in zend framework

Upvotes: 11

Views: 4795

Answers (2)

Ian Carter
Ian Carter

Reputation: 2169

A /sitemap.xml is just a regular route you need to add to module.config.php ...

'router' => [
    'routes' => [
        'sitemap' => [
            'type' => 'Literal',
            'options' => [
                'route'    => '/sitemap.xml',
                'defaults' => [
                    'controller' => 'Application\Controller\Sitemap',
                    'action'     => 'index',
                ],
            ],
        ],
    ],
],

... and a SitemapController.php

<?php
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class SitemapController extends AbstractActionController {
    public function indexAction() {
        $urls = [
            ['loc' => 'http://example.com/', 'lastmod' => date('Y-m-d'), 'changefreq' => 'daily', 'priority' => '1.0'],
            ['loc' => 'http://example.com/about', 'lastmod' => date('Y-m-d'), 'changefreq' => 'monthly', 'priority' => '0.8'],

            // TODO: here you likely want to generate URLs from filesystem or databases etc not do it manually including actual values for lastmod etc
            // if you have thousands of pages you likely should generate the XML considering maxitems, chunked sub-sitemaps etc
            // also ensure sane caching - you don't want this on demand
            // then there are also JIT-PUSH updates for single pages to consider (instead of waiting for crawlers)
        ];
        $xml = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');
        foreach ($urls as $url) {
            $urlElem = $xml->addChild('url');
            foreach ($url as $key => $value) {
                $urlElem->addChild($key, $value);
            }
        }
        $response = $this->getResponse();
        $response->getHeaders()->addHeaderLine('Content-Type', 'application/xml');
        return $response->setContent($xml->asXML());
    }
}

Upvotes: 0

Related Questions