roady
roady

Reputation: 597

Slim Framework -> XML output with correct headers

Writing an API to handle XML and JSON. I want the response to be in the format that the request uses.

Example - API Request header has: Accept: application/xml

The issue that is that the response always has Content-Type: application/json.

I want this to return Content-Type: application/xml

This is the code:

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 returns the following string:

<xml>
    <error>true</error>
    <errorType>Request doesn\'t exist, check the manual.</errorType>
    <errorMessage>2</errorMessage>
</xml>

Upvotes: 1

Views: 2730

Answers (2)

zak
zak

Reputation: 876

Or

 $this->app->response->withHeader("Content-Type",'application/xml');

Nowadays...

Upvotes: 0

Crackertastic
Crackertastic

Reputation: 4913

The problem is that you are not using break to get out of your switch after the correct case fires (assuming that $headerType is actually being set to application/xml) so your default case ends up running as well and reverts any changes made by the first case.

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');
    }
}

Upvotes: 3

Related Questions