Skip to content
Advertisement

How to convert XML to JSON in PHP

I want to convert som xml data into some pretty json data then output it into an api. The output is not the problem but it’s the formatting of the xml data. I’ve looked around, but haven’t gotten around making it as pretty as some of the online converters out there. this is the xml data structure:

JavaScript

This converter can do it: https://www.freeformatter.com/xml-to-json-converter.html#ad-output

But how does it make it so? I’ve been looking around for answers but my version just isn’t as pretty.. This is what I’ve tried so far, to get kind of close:

JavaScript

Advertisement

Answer

Is your XML always in that structure? Trying to write a universal XML to JSON translator is much, much harder than writing one for your specific use case.

If it’s always the same, just pick out the parts you need from the JSON structure by name, and put them in an array in whatever structure you want. For the XML input and JSON output you give in the question, the code is as simple as this:

JavaScript

Note the use of (string) to tell SimpleXML that you want the text content of an element or attribute, rather than an object representing it.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement