Save an xml response to a file instead of displaying in browser

Hi, i'm just thinking on generating an sitemap.xml to my /public folder

My code:

<?php

class SitemapController extends \Phalcon\Mvc\Controller
{
            public function generujSitemap() {
            $response = $this->response;
            $response->setHeader('Content-Type', "application/xml; charset=UTF-8");
            $sitemap = new \DOMDocument("1.0", "UTF-8");

        /* generating sitemap.xml */

            $sitemap->appendChild($urlset);
            $response->setContent($sitemap->saveXML());
            $response->setFileToSend($_SERVER["DOCUMENT_ROOT"].'/public/sitemap.xml', null, false);
            return $response->send();
        }
}

class IndexController extends \Phalcon\Mvc\Controller
{

 public function sitemapAction(){
          $this->view->disableLevel(View::LEVEL_MAIN_LAYOUT);
          $SiteMap = new SitemapController();
          return $SiteMap->generujSitemap();
       }
}

It gives me a proper sitemap in browser, but how to save it into to the server?

edited Jul '17

Just found out a workaround solution

file_put_contents($_SERVER["DOCUMENT_ROOT"].'/public/sitemap.xml',$sitemap->saveXML());

perhaps Phalcon offers a nicer way, so I'm not closing the topic yet

edited Jul '17
 $SiteMap = new SitemapController();
          return $SiteMap->generujSitemap();

Move it to some service really, or just this method to indexController, it's stupid that you create new controller and call method from it which is not really a controller.

And about your question, don't really see a problem with file_put_contents. You are generating this content as a string, so not sure what else can be used.

edited Jul '17

Thanks @Jurigag for your advice.

I removed the file_put_contents function and used this

$sitemap = new \DOMDocument("1.0", "UTF-8");
//...
$sitemap->save($_SERVER["DOCUMENT_ROOT"].'/public/sitemap.xml');

I think it's ok now

Yea i guess this is fine too.

Do you mean you want the file to be force-downloaded by the browser, instead of just displaying it?

Hi there, no, just save as file on server

Do you mean you want the file to be force-downloaded by the browser, instead of just displaying it?