如何回显sitemap.xml Cakephp3.1

How to echo sitemap.xml Cakephp3.1

我在 sitemapxml.xml 中设置 MIME 类型时遇到问题。我找到了this,但是没有效果:

$this->RequestHandler->respondAs('xml');
$this->response->header(['Content-type' => 'application/xml']);

我还尝试在 sitemap.ctp 视图的开头添加 header('Content-type:text/xml')

查看迁移指南:

RequestHandlerComponent now switches the layout and template based on the parsed extension or Accept header in the beforeRender() callback instead of startup().

Cookbook > Appendices > 3.1 Migration Guide > RequestHandlerComponent

所以这意味着您在那里设置的内容(无论在哪里,但可以肯定它不在 Controller::beforeRender() 回调中)将在控制器操作 运行 之后和视图之前被覆盖正在渲染。

有多种方法可以解决这个问题。

  1. 正确使用请求处理程序组件,即启用扩展解析并在您的 URL 中提供扩展,或发送适当的 Accept header.这样组件将设置正确的响应类型。

    这是推荐的方式!

    另见 Cookbook > Views > JSON and XML views

  2. 设置RequestHandlerComponent::$ext属性,在渲染之前正在评估,并会导致请求处理程序组件相应地设置响应类型,

    $this->RequestHandler->ext = 'xml';
    
  3. 使用RequestHandlerComponent::renderAs()指示请求处理程序组件使用配置的XML视图,这将覆盖beforeRender()中设置的"wrong"类型]回调。

    $this->RequestHandler->renderAs($this, 'xml');
    
  4. 不使用请求处理程序组件,直接在响应上设置响应类型object。

    $this->response->type('xml');
    

有趣,我看到 $this->response->type 有效 仅当直接设置 $this->render('view');