编写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>
答案 0 :(得分:3)
问题是,在正确的案例触发后,您没有使用break
退出switch
(假设$headerType
实际设置为application/xml
)所以你的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');
}
}
答案 1 :(得分:0)
或者
$this->app->response->withHeader("Content-Type",'application/xml');
...如今