ZF2 - how to correctly set headers?

不羁的心 提交于 2019-12-10 21:52:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!