Serialisation - MiguelFieira/AMO-HANDBOEK GitHub Wiki

Want to convert an XML or JSON file to an object? Symfony has built-in features for that. The required classes are in the Serializer namespace.

// These are commonly used classes used for serialisation, import the ones that you need.
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

The Serializer

The Serializer class is used for these file to object conversions and vice versa, let's make a new Serializer object and give it some unconfigured encoder and normalizer objects. This will work just fine in most situations.

$encoders = [new XmlEncoder(), new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];

$serializer = new Serializer($normalizers, $encoders);

Data to object

Let's deserialise XML into an object.

// In this example we simulate an XML file within our code
$data = <<<EOF
<element>
    <name>Oxygen</name>
    <number>8</number>
    <ismetal>false</ismetal>
    <stpstate>gas</stpstate>
</element>
EOF;

// This here returns an object of type Element
$element = $serializer->deserialize($data, Element::class, 'xml');

You can use any class for deserialisation, The above code would definitely work if Element was an entity. Just remember to import your classes.

Now, you probably want the user to upload an XML file instead of hardcoding it in your code. This can be achieved with a combination of what we learned in Forms and the Serializer.

// You could for example make a form like this with a FileType field
$form = $this->createFormBuilder()
    ->add('file', FileType::class)
    ->add('save', SubmitType::class, ['label' => 'Upload'])
    ->getForm();
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $data = file_get_contents(
        $form->getData()['file']->getRealPath()
    );
    $element = $serializer->deserialize($data, Element::class, 'xml');
    // We just dump the element to demonstrate that it works.
    dd($element);
}

Object to data

To convert an object to XML or JSON, call the serialize() method on you Serializer and pass the object and data format in the arguments.

$pony = new Pony();
$pony->setName('Rainbow Dash');
$pony->setSpecies('Pegasus');

$jsonContent = $serializer->serialize($pony, 'json');
⚠️ **GitHub.com Fallback** ⚠️