Something that was, at one time, fairly simple to figure out and find documentation for has become quite a bit more confusing and hard to find. This is one of the top search results for this topic, so I want to take the time to post a solution I was able to put together using the new Methods.
My use case is getting a list of published nodes of a certain content type and publishing them to a page as XML to be consumed by a third party.
Here are my declarations. Some of them might be superfluous at this point, but I'm not done upgrading the code as of yet.
<?php
namespace Drupal\my_events_feed\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Component\Serialization;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Response;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Entity\EntityTypeManager;
Here's the code to just feed the object into the XML
/**
* Class BuildXmlController.
*/
class BuildXmlController extends ControllerBase {
/**
* Builds the xml from an object
*/
public function build() {
$my_events = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties([
'status' => '1',
'type' => 'submit_an_event',
]);
$thisSerializer = \Drupal::service('serializer');
$serializedData = $thisSerializer->serialize($my_events, 'xml', ['plugin_id' => 'entity']);
$response = new Response();
$response->headers->set('Content-Type', 'text/xml');
$response->setContent($serializedData);
return $response;
}
}
If you need to massage the data, then you'll have to fill an array and make edits there. Of course, you can still serialize a standard library array.
/**
* Class BuildXmlController.
*/
class BuildXmlController extends ControllerBase {
/**
* Builds the xml from an array
*/
public function build() {
$my_events = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties([
'status' => '1',
'type' => 'submit_an_event',
]);
$nodedata = [];
if ($my_events) {
/*
Get the details of each node and
put it in an array.
We have to do this because we need to manipulate the array so that it will spit out exactly the XML we want
*/
foreach ($my_events as $node) {
$nodedata[] = $node->toArray();
}
}
foreach ($nodedata as &$nodedata_row) {
/* LOGIC TO MESS WITH THE ARRAY GOES HERE */
}
$thisSerializer = \Drupal::service('serializer');
$serializedData = $thisSerializer->serialize($nodedata, 'xml', ['plugin_id' => 'entity']);
$response = new Response();
$response->headers->set('Content-Type', 'text/xml');
$response->setContent($serializedData);
return $response;
}
}
Hope this helps.