Data exchange in CakePHP [XML & JSON]

I searched over the web as how to do it, but couldn’t get a clear information, finally it took a little bit of time but yes i was able to render xml and json.
You can have a look for Cakephp’s REST implementation here.
For XML
For XML you need to have a xml layout file in “app/views/layouts/xml/” folder. So i created one file, and name it default.ctp.
Add the following contents to the file.
<?php
echo header(‘Content-type: text/xml’);
e(‘<?xml version=”1.0″ encoding=”utf-8″ ?>’);
echo $content_for_layout;
?>
The code is pretty self explanatory, I have just added a header and set the content type ‘xml’, then added xml version and encoding type. The “$content_for_layout” is the variable which will replaced by xml data.
Now in controller, you need to need to include xml helper. Lets suppose you have an some function, you get the data through a REST call, all you need to do is, set the layout in function like-
<?php $this->layout = ‘xml/default’ ; ?>
Do the logic implementation part in the function and at the end set the variables for view.
Now in function view file, you need to set the data, like for example,
<?php echo $xml->serialize($variable); ?>
For JSON
Again for json , its almost the same procedure, all you need to do is, tell Cakephp about JSON, just add the following line in routes.php
Router::parseExtension(‘json’);
Since json is not default content-type in cakephp , we need to mention it,
$this->RequestHandler->setContent(‘json’,’text/x-json’);
Now create one folder under layouts (path “app/views/layouts/”)and name it as ‘json’, create one template file, i created as default.ctp and add the following code,
<?php header("Pragma: no-cache"); header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate"); header('Content-Type: text/x-json'); header("X-JSON: ".$content_for_layout); echo $content_for_layout; ?>
The above code will the set the appropriate headers for json.
In controller you don’t need to do any changes, in view template file, you just need to add the following code,
<?php echo $javascript->object($var); ?>
The code will create a json object.
Note : I wanted to send an URL through JSON, but was unable to do it properly, when data was getting converted to JSON, it used to add backslash to before the forward slash, like the example below,
url : http://example.com/abc
after JSON object creation
url : http:\/\/example.com\/abc
So, it was creating a problem for me, what I did is, I just encoded the URL using ‘urlencode’ function which replaces all non-alphanumeric characters with % and two hex digits and spaces by + , so now the url is generated as,
url : http:%2F%2Fexample.com%2Fabc
If you have any doubts, please feel free to ask!