October 14, 2015

In this article, we are going to discuss about how to return XML response to views in CakePHP. CakePHP is an open source web application framework. It follows the Model-View-Controller (MVC) approach and is written in PHP, modeled after the concepts of Ruby on Rails, and distributed under the MIT License.CakePHP uses well-known software engineering concepts and software design patterns, such as Convention over configuration, Model-View-Controller, Active Record, Association Data Mapping, and Front Controller.

Step 1:

Open the file "app\Config\routes.php" and added the following line:

/**
 * Parse XML Routes
 */
Router::parseExtensions('xml');

This enables your Controller actions to start accepting the .xml postfix e.g. http://cakephp_app/controller/action.xml

Step 2:

Enable the RequestHandler component in your Controller like this:

public $components = array('RequestHandler');

Step 3:

Once that's done, you have a few more methods at your disposal to start dealing with XML requests. First create a beforeFilter method in your Controller and add the following:

public function beforeFilter() {
    parent::beforeFilter();

    // Set XML
    if ($this->RequestHandler->isXml()) {
       $this->RequestHandler->setContent('xml');
    }
}

Step 4:

Once that's done, create the action that you want to use and be sure to add in the respondAs & renderAs methods as the official documentation is a bit flakey with their use:

public function related() {
    // Only allow XML requests
    if (!$this->RequestHandler->isXml()) {
        throw new MethodNotAllowedException();
    }

    // Set response as XML
    $this->RequestHandler->respondAs('xml');
    $this->RequestHandler->renderAs($this, 'xml');
}

Step 5:

Using those 2 methods as I was then able to create an xml folder in the corresponding View folder and inside that create my view file e.g. app\View\Uploads\xml\related.ctp

<?xml version="1.0"?>
<people>
<person>
<name>James</name>
</person>
</people>

Now if you visited the page in your browser you should see your XML output as per your View e.g. http://cakephp_app/uploads/related.xml

Wrapping Up

Further to this if you wanted to pass in some parameters to make the Controller action dynamic you can do by using the following e.g. http://cakephp_app/uploads/related/videos/1.xml

The "videos" parameter and the "1" ID will be available in the Controller like this:

// Get passed params
$uploadType = $this->request->params['pass'][0];
$uploadId = $this->request->params['pass'][1];
Next
This is the most recent post.
Older Post

0 comments:

Post a Comment