【问题标题】:How to set Content-Type in Slim to XML?如何将 Slim 中的 Content-Type 设置为 XML?
【发布时间】:2021-04-26 07:04:24
【问题描述】:

我想将application/xml 输出为Content-Type 用于我的Slim 输出。下面你会看到我生成输出的代码。不幸的是,所有被注释掉的代码都不能输出相应的 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();

【问题讨论】:

    标签: php xml rss slim


    【解决方案1】:

    这应该可行:

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

    【讨论】:

    • 感谢您的回复!不幸的是,当查看网络选项卡中的标题时,这不会改变输出:Content-type: text/html; charset=UTF-8
    • 它必须像这样工作。否则,另一个中间件正在更改内容类型,或者它是网络服务器(配置)或防火墙特定问题。
    • 感谢您的帮助!我发现错误:关闭 PHP 标记后有一个空格。这样,空白空间是 slim 之前的第一个输出,因此标题设置为 text/html。感谢您帮我在 slim 代码之外搜索错误!
    • 好吧好吧。这就是为什么不应再使用关闭 PHP 标记的原因。
    【解决方案2】:

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

    <?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();
    

    【讨论】:

    • 感谢您的回复!不幸的是,当查看网络选项卡中的标题时,这不会改变输出:Content-type: text/html; charset=UTF-8
    • 感谢您的帮助!我发现错误:关闭 PHP 标记后有一个空格。这样,空白空间是 slim 之前的第一个输出,因此标题设置为 text/html。感谢您帮我在 slim 代码之外搜索错误!
    • 防止此类错误的常见做法是避免在 php 文件中使用结束标记。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 2010-12-08
    • 2014-08-22
    • 2012-07-08
    • 1970-01-01
    相关资源
    最近更新 更多