Slim中如何设置Content-Type为XML?

How to set Content-Type in Slim to XML?

我想输出 application/xml 作为我的 Slim 输出的 Content-Type。在下面,您会看到生成输出的我的代码。不幸的是,所有被注释掉的代码都无法输出相应的 Content-Type。你有什么建议吗?

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use \Slim\Helper\Set;

require 'vendor/autoload.php';

use Psr7Middlewares\Middleware\TrailingSlash;


$app = AppFactory::create();

$app->get('/{show}/feed', function(Request $request, Response $response, $args) use($app) {

    $html = '<?xml version="1.0" encoding="utf-8" ?><sampletag></sampletag>';

    // $app->response->headers->set('Content-Type', 'application/xml');
    // $response = $response->withHeader('Content-type', 'application/xml');
    $response->getBody()->write($html);
    
    // return $response->withStatus(201)->withHeader('Content-Type', 'application/xml')->getBody()->write($html);
    return $response;
});

$app->run();

这应该有效:

$response = $response->withHeader('Content-Type', 'application/xml');

您已注释掉负责向响应中添加所需 headers 的行。以下工作正常:

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use \Slim\Helper\Set;

require 'vendor/autoload.php';

use Psr7Middlewares\Middleware\TrailingSlash;


$app = AppFactory::create();

$app->get('/{show}/feed', function(Request $request, Response $response, $args) use($app) {

    $html = '<?xml version="1.0" encoding="utf-8" ?><sampletag></sampletag>';
    // Do not comment out the following line
    $response = $response->withHeader('Content-type', 'application/xml');
    $response->getBody()->write($html);
    return $response;
});

$app->run();