无法覆盖内容类型 PHP 服务器标头


Can't override content-type PHP server headers

当前服务器返回以下标头,如下所示:

2014-11-13 00:20:04.079 myiOSApplication 46715:1003]:

{ status code: 200, headers {
    Connection = close;
    "Content-Length" = 5;
    "Content-Type" = "text/html; charset=UTF-8";
    "Content-Typesss" = "application/json; charset=UTF-8"; //<-- Notice this appears, but soon as I remove the extra s characters, then it wont override the line above. :( so the content always returns `text/html` instead of the desired `application/json`
    Date = "Thu, 13 Nov 2014 00:20:03 GMT";
    Server = "Apache/2.2.26 (Amazon)";
    Status = "200 OK";
    StatusCode = 200;
    "X-Powered-By" = "PHP/5.3.28";
} }

我可以轻松设置其他标头,但是当我尝试使用键设置标头时,Content-Type如下所示:

header('Content-Type : application/json; charset=UTF-8');
然后我的密钥

被系统密钥覆盖并忽略我的标头类型。

我能做什么?

更新 1:

回应@scuzzy的要求——

如果你回显你的标头然后退出()会发生什么; 脚本? 例如 header('Content-Type : application/json; charset=UTF-8');exit('{"hello":"world"}');

以下是iOS对此的回应:

2014-11-13 00:59:25.801 myiOSApplication [46849:1f07] RESPONSE: <NSHTTPURLResponse: 0x61800002c060> { URL: http://www.riabp.com/KINGS/Secure/Rajam/Get/Employees } { status code: 200, headers {
    Connection = close;
    "Content-Length" = 18;
    "Content-Type" = "text/html; charset=UTF-8";
    Date = "Thu, 13 Nov 2014 00:59:25 GMT";
    Server = "Apache/2.2.26 (Amazon)";
    "X-Powered-By" = "PHP/5.3.28";
} }
2014-11-13 00:59:25.801 KingsEMS[46849:303] Error: Request failed: unacceptable content-type: text/html
2014-11-13 00:59:25.801 KingsEMS[46849:303] JSON Error:     {"hello":"world"}

我不确定这是否仍然是一个活跃的问题,但我遇到了类似的问题,即 PHP 为 text/html 设置了内容类型标头,但是当我想下载图像时,使用 PHP,我无法将标头内容类型更新为 image/gif,因此文件已下载但无法打开。

最后的答案是返回输出缓冲区并确保它是空的:

$html = ob_get_clean();
$html = str_replace(" ", "", $html);

我假设代码中的某处有一些空格,迫使输出保留为原始内容类型。

理查

更新:这应该在设置新的标头值之前添加,以防这不明显。

如果你正在使用像Silex或Zend等这样的框架,或者只是编写普通的php代码,并且你正在使用这些函数

 json_encode($query)         //php json function
 $app->json($query)          //Silex framework function`

但这些都不能解决你接收json内容类型的需要,有一个小技巧可以帮助你:

     header('Content-Type: application/json');  //before everything
     $query =....                              //retrieve your data in every way you need
     $queryjsoned=json_encode($query);    //jsonify your query
     exit($json);                      //it's very important,it solves your life
     return $queryjsoned;             //if you are in a function/Route,but it isn't mandatory

很奇怪,您需要执行退出来覆盖内容类型。

非常老的问题,但我最近遇到了一个问题。以防万一有人遇到这个问题并且解决方案(对我来说)如此简单,这里是:如果您使用 PHP 包含文件,例如

包括("配置.php");

确保末尾不包含 PHP 结束标记 (?>),除非你需要它。这将防止 PHP 结束标记"?>"中所述的"不需要的空格"。这样的空格将触发 PHP 中默认的 MIME 类型配置。

就我而言,我确实有一个结束标签,后面有一个空行。删除多余的行解决了问题(现在使用声明的内容类型标头)。