In a CakePHP project, I needed to extract an XML string from the database and display it as an XML page. The docs suggested this would be easy with the XmlView, but I struggled to get it to work. However, after a fair amount of fiddling around, I found an easy way to display an XML view.
Here’s what I had to do:
- Enable parsing of .xml extensions in routes.php:
- Set the viewClass to Xml in the controller:
$this->viewClass = 'Xml';
- Create a simple xml view in Views/YourController/xml/xml.ctp, and echo $xml in this view:
<?php echo $xml; ?>
- Back in the controller, set the XML string to the view:
- Finally, render using the xml view you have just created (this must be after the ‘set’ line above):
Unfortunately, this does not take advantage of the _serialize key, which would mean you don’t need to create a view file at all, but I just couldn’t get this to work with an XML string, despite trying various combinations of CakePHP’s Xml Class functions.
2 Replies to “XML views in CakePHP 2.x”
It is fairly easy to not use a view template. Simply follow the documentation regarding _serialize.
See https://github.com/dereuromark/cakephp-sandbox/blob/master/Controller/ExportController.php#L52 for an example.
Two lines of code.
Thanks, I did try this, but I couldn’t get it to work with an XML string. I’m not getting an array from the database and converting this to XML, I just have XML stored in a text field in the database (it has to be this way). I tried various things, (
$this->set('_serialize', Xml::build($xmlString));, or
build, or both, seemed the most likely options), but just couldn’t seem to get the XML into a format that _serialize was happy with.
I may well be missing something simple, so if you have any thoughts on what I might be doing wrong, that would be much appreciated.