Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
ZF2 How to return XML response
<?php
$rawXml = '<foo><bar>Baz</bar></foo>';
$response = new \Zend\Http\Response();
// Instead of header("Content-type: text/xml; charset=utf-8") use:
$response->getHeaders()->addHeaderLine('Content-Type', 'text/xml; charset=utf-8');
$response->setContent($rawXml);
return $response;
<?php
namespace SomeNamespace\Controller;
use Zend\View\Model\JsonModel;
use Zend\View\Model\FeedModel;
use AP_XmlStrategy\View\Model\XmlModel;
class SomeController extends AbstractActionController
{
protected $acceptCriteria = array(
'Zend\View\Model\JsonModel' => array(
'application/json',
),
'Zend\View\Model\FeedModel' => array(
'application/rss+xml',
),
'AP_XmlStrategy\View\Model\XmlModel' => array(
'application/xml',
),
);
public function apiAction()
{
$viewModel = $this->acceptableViewModelSelector($this->acceptCriteria);
if ($viewModel instanceof JsonModel) {
return new JsonModel(array(
'response' => 'foo',
)
);
}
if ($viewModel instanceof FeedModel) {
return new FeedModel(array(
'response' => 'foo',
)
);
}
if ($viewModel instanceof XmlModel){
return new XmlModel(array(
'response' => 'foo',
)
);
}
}
}
<?php
namespace Chart\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use XMLWriter;
class IndexController extends AbstractActionController
{
public function graphAction()
{
$rawXml = '<foo><bar>Baz</bar></foo>';
$writer= new XmlWriter();
$writer->openMemory();
$writer->startDocument('1.0', 'UTF-8');
$writer->writeRaw($rawXml);
$writer->endDocument();
$response = $this->getResponse();
$response->getHeaders()->addHeaders(array('Content-type' => 'text/xml'));
$response->setContent($writer->outputMemory());
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment