1

How do I create a page that returns an XML feed?

6

Can you give more details ?

For example for an aggregator RSS :

In your test.routing.yml :

test.rss:
  path: '/rss'
  defaults:
    _title: 'rss'
    _controller: '\Drupal\test\Controller\RssController::content'
  requirements:
    _access_test: 'test'

And in your controller :

<?php

namespace Drupal\test\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

class RssController extends ControllerBase
{
    public function content()
    {
        $response = new Response();
        $response->setContent('<?xml> My flux </xml>');
       // kint($response);
        return $response;

    }

}

You need the HttpFoundation\Response component.

  • Just noting, be sure to set the XML content type header or try use Symfony\Component\HttpFoundation\XmlResponse; and return new XmlResponse($response); – David Thomas Feb 7 '18 at 21:57
  • This is returning HTML for me with the <?xml ...> header being commented out. – Chris Happy Mar 27 '18 at 1:39
2

Kevin's answer caused my Twig template's <?xml ...> tag to be commented out. I had to add to make the page render it as XML.

$response->headers->set('Content-Type', 'text/xml');

Full example for my module named custom.

custom.routing

# My XML controller
custom.my_xml_feed:
  path: '/xml-feed'
  defaults:
    _controller: '\Drupal\custom\Controller\XMLfeed::content'
  requirements:
    _permission: 'access content'

XMLfeed.php

<?php

namespace Drupal\custom\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

class XMLfeed extends ControllerBase {


  public function content() {
    $rows = [];

    $build = [
      '#theme' => 'my_theme_template',
      '#rows' => $rows,
      '#cache' => ['max-age' => 0],
    ];

    $output = \Drupal::service('renderer')->renderRoot($build);

    $response = new Response();
    $response->setContent($output);
    $response->headers->set('Content-Type', 'text/xml');

    return $response;
 }

}

Not the answer you're looking for? Browse other questions tagged or ask your own question.