I'm receiving a JSON string in a PHP page :
$JSON = $_POST['submit'];
$Array = json_decode($JSON);
$xml = arrayToXML($Array,"","root");
echo $xml;
where arrayToXML is a function I made for the puropose.
The function works fine, but there are a couple problems I'd like to fix:
1.Duplicate Tags:
Let's say we have a JSON string such as
{element:[{sub1:xxxx,sub2:xxx},{sub1:xxxx,sub2:xxx},{sub1:xxxx,sub2:xxx}]}
the corresponding XML would be like
<element>
<sub1>xxxx</sub1>
<sub2>xxx</sub2>
</element>
<element>
<sub1>xxxx</sub1>
<sub2>xxx</sub2>
</element>
<element>
<sub1>xxxx</sub1>
<sub2>xxx</sub2>
</element>
But the recursion of my function duplicates the first tag and the last one. I can see why it does so, but I can't figure out a way to fix it. So I solved this by preg_replacing duplicate tags. Is there a better way to fix this? It's really been couple days I've been thinking on this.
2. Indentation:
I wanted the function to generate the xml in a fancy human readable way, so I put newlines between adjacent tags, but how can I define correct nested indentation?
I tryied this:
$xml = preg_replace("/(\t*)(<\/?.+>)(<\/?.+>)/","$2\n$1\t$3",$xml);
but turns out to be compleately wrog. What would be a correct one?
Many thanks.