Hello!!!
How to display content in xml files??? This requires a custom template engine???
|
May '13 |
3 |
3705 |
3 |
Hi,
Printing just the XML:
public function showAsXmlAction()
{
$response = new Phalcon\Http\Response();
$response->setHeader('Content-Type', 'application/xml');
$response->setContent('<root><element><key>a</key><value>b</value></element></root>');
return $response;
}
From a DOMDocument:
public function showAsXmlAction()
{
$response = new Phalcon\Http\Response();
$doc = new DOMDocument();
$doc->loadXML('<root><element><key>a</key><value>b</value></element></root>');
$response->setHeader('Content-Type', 'application/xml');
$response->setContent($doc->saveXML());
return $response;
}
There are several ways to accomplish that:
class MyController extends Phalcon\Mvc\Controller
{
public function showAsXml1Action()
{
return "<root><key>k</key></root";
}
public function showAsXml2Action()
{
return "<root><key>k</key></root";
}
public function afterExecuteRoute($dispatcher)
{
$response = new Phalcon\Http\Response();
$response->setHeader('Content-Type', 'application/xml');
$response->setContent($dispatcher->getReturnedValue());
$dispatcher->setReturnedValue($response);
}
}
class MyXMLResponse extends Phalcon\Http\Response
{
public function __construct($xml)
{
$this->setHeader('Content-Type', 'application/xml');
$this->setContent($xml);
}
}
in controller:
public function showAsXml2Action()
{
return MyXmlResponse("<root><key>k</key></root");
}
class MyController extends Phalcon\Mvc\Controller
{
public function showAsXml1Action()
{
return array(
"type" => "xml",
"content" => "<root><key>k</key></root"
);
}
}
Plugin:
<?php
class ContentTypePlugin extends \Phalcon\Mvc\User\Plugin
{
public function afterExecuteRoute($event, $dispatcher)
{
$content = $dispatcher->getReturnedValue();
switch ($content['type']) {
case 'xml':
$response = new Phalcon\Http\Response();
$response->setHeader('Content-Type', 'application/xml');
$response->setContent($content['content']);
$dispatcher->setReturnedValue($response);
break;
}
}
}
/**
* @Response(type="xml")
*/
public function showAction()
{
return "<root><key>k</key></root";
}
Plugin:
<?php
class AnnotationsContentPlugin extends \Phalcon\Mvc\User\Plugin
{
public function afterExecuteRoute($event, $dispatcher)
{
$annotations = $this->annotations->getMethod(
$dispatcher->getActiveController(),
$dispatcher->getActiveMethod()
);
//Check if the method has an annotation 'Response'
if ($annotations->has('Response')) {
//Get the type
$type = $annotations->get('Response')->getNamedParameter('type');
if ($type == 'xml') {
$response = new Phalcon\Http\Response();
$response->setHeader('Content-Type', 'application/xml');
$response->setContent($dispatcher->getReturnedValue());
$dispatcher->setReturnedValue($response);
}
}
}
}