i am curious to know how can i get the database data in xml format in Zend framework using context switching.
Do i need to compulsorily specify the format in my url, like:
http://localhost/pt/public/index.php/api/v1/users.xml?param1=3
I want to get the format from url (.xml, .json...) and apply the corresponding format to my output automatically.
Currently iam doing this: I get the user data from the database. I get the users marks based on the class id i pass to the url:
$id = $request->getParam('param1'); // get class id param
$users = new Application_Model_DbTable_Users();
$result = $users->fetchData($id);
if(count($result) != 0)
{
$doc = new DOMDocument();
$doc->formatOutput = true;
$root = $doc->createElement("Student");
$doc->appendChild($root);
foreach($result as $details)
{
$root_element = $doc->createElement("Marks");
$root->appendChild($root_element);
$TElement = $doc->createElement("Total");
$TElement->appendChild($doc->createTextNode($details->marks));
$root_element->appendChild($TElement);
}
$xml = $doc->saveXML();
$this->view->xml = $xml;
}
And in the corresponding view script, i have this code:
<?php
header('Content-type: text/xml');
echo $this->xml;
?>
I get the user data and use DOMDocument to write the xml output to the view. But is it possible to automatically generate the XML data from database, without using DOM ?
emaillenin is right, there's nothing ZF
can do to convert your data to XML.
But instead of forming XML
manually (with DOMDocument
and the like), I suggest that you take a look at PEAR XML_Serializer package.
XML_Serializer
allows you to transform arrays, objects, etc. to well-formed XML
. You can also specify your root name, default tag names, indentation type, etc. So, you're pretty much in control for the resulting XML
.
Zend context switching helps in changing your headers, disabling layout and those kind of helps. It does not help in returning the database data as XML data.
The following code can be used to return XML output once you have converted your DB data into XML formatted data with tags.
class OutputController extends Zend_Controller_Action
{
public function xmlAction()
{
$xml = simplexml_load_string($sourceData);
$output = $xml->saveXML();
Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
$this->_helper->layout->disableLayout();
Zend_Layout::getMvcInstance()->disableLayout();
header('Content-Type: text/xml');
echo $output;
exit();
}
}
I will update the answer if you provide more information about how you retrieve the data from DB and what format of XML (the hierarchy of tags) you want in the output.