简体   繁体   中英

ZF2 - how to correctly set headers?

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?

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

Try -

public function xmlAction()
{
    $this->getResponse()->getHeaders()->addHeaders(array('Content-type' => 'application/xml'));

    echo $file; // xml file content
    exit;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM