编写一个API来处理XML和JSON。我希望响应采用请求使用的格式。
示例-API请求头具有:Accept: application/xml
问题是响应总是具有Content-Type: application/json
。
我想让它返回Content-Type: application/xml
这是代码:
public function setHeaders() {
$headerType = $this->app->request->headers->get('Accept');
switch($headerType){
case "application/xml":
$this->app->response->headers->set("Content-Type",'application/xml');
default:
// default type is application/json
$this->app->response->headers->set("Content-Type",'application/json');
}
}
# 404 errors
$app->notFound(function () use ($app) {
$logMessage = sprintf("404 Not Found: URI: %s", $app->request->getPath());
$app->log->debug($logMessage);
$error = new 'SMSTester'ErrorVO(2,"Request doesn''t exist, check the manual.");
$app->parser->setHeaders();
$app->halt(404,$app->parser->outputParse($error));
});
outputParse
返回以下字符串:
<xml>
<error>true</error>
<errorType>Request doesn''t exist, check the manual.</errorType>
<errorMessage>2</errorMessage>
</xml>
问题是,在正确的案例激发后(假设$headerType
实际上被设置为application/xml
),您没有使用break
来退出switch
,因此您的default
案例最终也会运行,并恢复第一个案例所做的任何更改。
public function setHeaders() {
$headerType = $this->app->request->headers->get('Accept');
switch($headerType){
case "application/xml":
$this->app->response->headers->set("Content-Type",'application/xml');
break; //Break here prevents the next case from firing
default:
// default type is application/json
$this->app->response->headers->set("Content-Type",'application/json');
}
}
或
$this->app->response->withHeader("Content-Type",'application/xml');
如今。。。