0

I'm having a Json:

[{"S":"a","D":"b"},{"S":"s1","D":"m1"},{"S":"2","D":"3"},{"S":"4","D":"5"}]

And I want it to convert into XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<Us>
    <U1>
        <S>a</S>
        <D>b</D>
    </U1>
    <U1>
        <S>s1</S>
        <D>m1</D>
    </U1>
</Us>

I know the php way, first decoding json using Json_decode() and a bunch of foreach loop that finally generate XML.

But I want in Drupal way. There is a module serialization in core of Drupal 8. But don't know how can I take the services from that module in my custom one.

Also, I got a link, How to get it done using symfony, but again it seems like Drupal 8 standards are lacking somewhere by me.

What's the right approach to achieve this in Drupal way.

  • Is your data normalized and does it need to be denormalized into data that Drupal understands (such as a node, user, taxonomy term, etc...)? – mradcliffe Sep 15 '16 at 12:51
  • Serializer is also a perfectly fine way of doing this in Drupal 8. The serialization module uses that component. – mradcliffe Sep 15 '16 at 12:51
  • It's like, when saving, I saved into database in json format but now when I'm retrieving, I want it in xml. It's fine with me to decode it first and get an array structure, (I'm getting 1 array of multiple objects), but now how to convert it into xml is a little challenging with best approach. – Sugandh Khanna Sep 15 '16 at 13:03
0

The Serializer component is a tool in your Drupal toolbox that should be used when you need to serialize and deserialize data from and to Drupal data such as entities. Unfortunately you cannot deserialize into a \StdClass without implementing your own normalizer.

Inject the serializer service into your class, and use the serialize method to normalize the non-Drupal decoded JSON array into XML.

// Inject this instead of using \Drupal
$serializer = \Drupal::get('serializer');
// Use json_decode or @4k4's example above and use associative arrays instead of object.
$json = json_decode('[{"S":"a","D":"b"},{"S":"s1","D":"m1"},{"S":"2","D":"3"},{"S":"4","D":"5"}]', TRUE);
// Unfortunately it seems that for an array serializer xml_root_node_name won't work so wrap $json in the root name.
$data = ['US' => $json];
// Serialize into XML.
$xml = $serializer->serialize(
  $data,
  'xml',
  ['xml_root_node_name' => 'US']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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