XML views in CakePHP 2.x

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:
    Router::parseExtensions('xml');
  • 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:
    $this->set('xml', $xmlString);
  • Finally, render using the xml view you have just created (this must be after the ‘set’ line above):
    $this->render('xml');

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”

    1. Hi Mark,

      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 toArray instead of 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.

      Thanks,

      Jon

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.