Skip to content

Instantly share code, notes, and snippets.

@davidbarratt
Created February 28, 2015 22:34
Show Gist options
  • Save davidbarratt/a1e805aef086d535b8c3 to your computer and use it in GitHub Desktop.
Save davidbarratt/a1e805aef086d535b8c3 to your computer and use it in GitHub Desktop.
Entity Export using Serialization
<?php
use Drupal\node\Entity\Node;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\serialization\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncode;
$node = Node::load(4);
$data = $node->toArray();
if ($node->getEntityType()->hasKey('id')) {
unset($data[$node->getEntityType()->getKey('id')]);
}
if ($node->getEntityType()->hasKey('revision')) {
unset($data[$node->getEntityType()->getKey('revision')]);
}
$encoders = array(new XmlEncoder());
$normalizers = array(new ContentEntityNormalizer(\Drupal::service('entity.manager')));
$serializer = new Serializer($normalizers, $encoders);
$xml = $serializer->serialize($data, 'xml');
file_put_contents('node.xml', $xml);
<?php
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\serialization\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncode;
$data = file_get_contents('node.xml');
$encoders = array(new XmlEncoder());
$normalizers = array(new ContentEntityNormalizer(\Drupal::service('entity.manager')));
$serializer = new Serializer($normalizers, $encoders);
$node = $serializer->deserialize($data, 'Drupal\node\Entity\Node', 'xml', array(
'entity_type' => 'node',
));
$node->save();
@Strutsagget
Copy link

Don't think these works anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment