php - ZF2 - 如何正确设置标题?

标签 php zend-framework2 http-headers

我在 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/

相关文章:

php - 生成验证码图像 PHP

php - PDOStatement::fetch 偶尔会返回 false,但 errorInfo() 为空

php - ZF2 Zend\Log + Doctrine2

http - 在浏览 session 期间查看请求/响应 header 的实用程序?

c++ - 带套接字的 POST 请求

php - 我如何使用 PHP 从 mysql 数据库中检索和显示时间戳?

php - 从 Zend Framework 1 迁移到 Zend Framework 2

cookies - Zf2 - 如何设置 cookie

http-headers - 确定网站访问者操作系统的最可靠方法是什么?

PHP exec() 没有从 bash 命令获取输出