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

时间:2014-11-13 00:30:26

标签: php header http-headers content-type server

目前服务器返回以下标题,如下所示:

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的 -

请求

如果您回显标题然后退出(),会发生什么?剧本?例如标题(&#39; Content-Type:application / json; charset = UTF-8&#39;);退出(&#39; {&#34; hello&#34;:&#34; world&#34;} &#39);

以下是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"}

2 个答案:

答案 0 :(得分:1)

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

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

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

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

理查德

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

答案 1 :(得分:0)

如果您使用的是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

非常奇怪的是,您需要退出以覆盖内容类型。

相关问题