1
votes

I'm trying to automatically generate a sitemap with CakePHP 2.1, i changed the header response to text/xml but the browser is getting a text/html response.

SitemapsController :

<?php 
class SitemapsController extends AppController{ 

    var $uses = array('Post'); 
    var $helpers = array('Time'); 
    var $components = array('RequestHandler'); 

    function index (){ 

        Configure::write ('debug', 0);

        $this->set('posts', $this->Post->find('all', array('conditions'=>array('publique'=>1))));

        $this->RequestHandler->respondAs('xml');

    }

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow();
    }
    public function isAuthorized($user) {
        return true;
    } 
} 
?>

/view/Sitemaps/xml/index.ctp

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url> 
        <loc><?php echo Router::url('/',true); ?></loc> 
        <changefreq>daily</changefreq> 
        <priority>1.0</priority> 
    </url>     
    <?php foreach ($posts as $post):?> 
    <url> 
        <loc><?php echo Router::url(array('action'=>'view', 'id'=>$post['Post']['id'], 'slug'=>$post['Post']['slug']),true); ?></loc> 
        <lastmod><?php echo $this->Time->toAtom($post['Post']['created']); ?></lastmod> 
        <priority>0.8</priority> 
    </url> 
    <?php endforeach; ?> 
</urlset>

Layouts/xml/default.ctp

<?php header('Content-type: text/xml'); ?> 
<?= $this->fetch('content'); ?>

routes.php

Router::parseExtensions('xml');
Router::connect('/sitemap',array('controller'=>'sitemaps','action'=>'index','url'=>array('ext'=>'xml')));
2

2 Answers

0
votes

Have you tried to set the complete content-type in the requestHandler ?

$this->RequestHandler->respondAs('application/xml');

Because it's necessary depending of your associated models. Or try to pass the option array :

RequestHandlerComponent::respondAs($type, $options)¶
Parameters: 
$type (string) – Friendly content type name ex. xml, rss or a full content type like application/x-shockwave
$options (array) – If $type is a friendly type name that has more than one content association, $index is used to select the content type.
-1
votes
$this->response->type('text/xml');