Monday, August 1, 2011

XML Output with the Yii Framework

My quick solution for getting the Yii Framework to display XML data.

I'm just going to give the code from a project that I'm working, so substitute in your own names where necessary.

Overview
Files to create:

  • protected/views/[your_class]/[your_action].php
  • protected/views/layouts/[your_xml_layout].php

Files to modify:

  • protected/controllers/[your_controller].php

In general, the approach is as follows. Create a layout that wraps our XML and outputs the XML header.

Step 1: Create The View Files
For the layout file, make sure you have at least the bolded text below included:

File: protected/views/layouts/[your_xml_layout].php
<?php header("Content-type: text/xml"); ?>
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'?>
<Response>         
        <Tag><?php echo $content; ?></Tag>
</Response>

I'll leave it up to you to figure out how you want to wrap your data with xml tags.

Next, create the view file for the action. This can be as complex as you want it to be. Here's an extremely simple example showing the output of just one variable.

File: protected/views/[your_class]/[your_action].php
<?php echo CHtml::encode($model->getAttributeLabel('name')); ?>: 
<?php echo CHtml::encode($model->name); ?>

Step 2: Edit the Controller
Now you want to tell your controller which files to use. Create a new action in your controller and make sure you assign both the layout file you created and the action view.

For example:
public function action[your_action]($id)
{
  $this->layout = "[your_layout]";
  $this->render('[your_action]',array('model'=>$this->loadModel($id)));
}

Lastly, make sure that you have allowed access to your new action if that's a necessity.

If others have a better means of doing this, do let me know in the comments and I'll update this howto.

Further Reading

I found the following pages for reference when investigating the issue to begin with.
http://www.kirupa.com/web/mysql_xml_php.htm
http://www.yiiframework.com/forum/index.php?/topic/4664-xml-output/

No comments: