曾经一度相当容易找出和查找文档的东西变得更加混乱和难以查找。这是该主题的热门搜索结果之一,因此,我想花些时间发布使用新方法可以汇总的解决方案。
我的用例是获取某种内容类型的已发布节点的列表,并将它们作为XML发布到页面上,以供第三方使用。
这是我的声明。在这一点上,其中一些可能是多余的,但是到目前为止,我还没有完成代码的升级。
<?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;
这是将对象馈入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;
}
}
如果需要处理数据,则必须填充一个数组并在那里进行编辑。当然,您仍然可以序列化标准库数组。
/**
* 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;
}
}
希望这可以帮助。