问题
I have problem with setting headers in ZF2. My code looks like this:
public function xmlAction()
{
$headers = new \Zend\Http\Headers();
$headers->clearHeaders();
$headers->addHeaderLine('Content-type', 'application/xml');
echo $file; // xml file content
exit;
}
But headers are still text/html. I can set the proper header with:
header("Content-type: application/xml");
but I would like to do it with Zend Framework. Why code above doesn't work?
回答1:
What you are doing is setting headers in a ZF2 Response object, but this response is later on never used. You are echoing a file and then exiting, so there is no chance for ZF2 to send the response (with its headers).
You have to use the response to send the file, which you can do like this:
public function xmlAction()
{
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('Content-Type', 'application/xml');
$response->setContent($file);
return $response;
}
The idea of returning the response from a controller method is called "short circuiting" and is explained in the manual
回答2:
Try -
public function xmlAction()
{
$this->getResponse()->getHeaders()->addHeaders(array('Content-type' => 'application/xml'));
echo $file; // xml file content
exit;
}
来源:https://stackoverflow.com/questions/24218171/zf2-how-to-correctly-set-headers