October 28, 2013

October 28, 2013
In this article, we are going to discuss about How to Save page output as HTML with cakePHP. As of now, I am working on a project that requres store the dynamically created output HTML files on a CDN (Content Delivery Network). I need to dynamically create a HTML page with database data and then store that HTML file on a CDN (Amazon S3) which cannot parse PHP. 

I was looking for a way to output a view, and save it as an HTML file which could then be uploaded via the S3 API. In the CakePHP API, we see the Controller render method returns the output of the View model's render method which returns a string of the HTML output to be loaded in the browser. But we don't want to call the Controller's render method as that will send the user's browser to that page. Instead we want to use the View's render method so we get the string value that can be saved into an HTML file.

Assume we have a publish controller method which is called when the user wants to publish the HTML file. We also have a private method to generate the HTML and save it as a file in the local filesystem.

<?php
class VideosController extends AppController {

    protected function publish( $id ){
        $html_file = $this->generate( (int)$id );
        //do whatever needs to be done with the HTML file
        //for example, this is where I upload the file to S3
    }

    private function generate( $id ){
        //set whatever data is required to build the page;
        //be sure this is done before instantiating the View class so all
        //set variables are passed when you pass this controller object in the constructor
        $video = $this->Video->read( null, $id );
        $this->set('video', $video);

        //instantiate a new View class from the controller
        $view = new View($this);

        //call the View object's render method which will return the HTML.
        //Note, I'm setting the layout to HTML and telling the view to render the html.ctp file in /app/views/videos/ directory
        $viewdata = $view->render(null,'html','html');

        //set the file name to save the View's output
        $path = WWW_ROOT . 'files/html/' . $id . '.html';
        $file = new File($path, true);

        //write the content to the file
        $file->write( $viewdata );

        //return the path
        return $path;

    }
}

Let me know if you run into any problems. But so far, seems to be working well.

0 comments:

Post a Comment