我在 ZF2 中设置 header 时遇到问题。我的代码如下所示:
public function xmlAction()
{
$headers = new \Zend\Http\Headers();
$headers->clearHeaders();
$headers->addHeaderLine('Content-type', 'application/xml');
echo $file; // xml file content
exit;
}
但标题仍然是文本/html。我可以设置正确的 header :
header("Content-type: application/xml");
但我想用 Zend Framework 来做。为什么上面的代码不起作用?
最佳答案
您正在做的是在 ZF2 Response
对象中设置 header ,但此响应稍后从未使用过。您正在回显文件然后退出,因此 ZF2 没有机会发送响应(及其 header )。
您必须使用响应来发送文件,您可以这样做:
public function xmlAction()
{
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('Content-Type', 'application/xml');
$response->setContent($file);
return $response;
}
从 Controller 方法返回响应的想法称为“短路”并且是 explained in the manual
关于php - ZF2 - 如何正确设置标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24218171/