Reputation: 2250
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.
Upvotes: 0
Views: 438
Reputation: 581
refering to the first doubt "duplicate tag", I think that the best that you can do is to change the JSON string to the right structure you need, if you need more than one phone number element change the JSON string to have more than a phone number element, perhaps you can do something like preg_replace or identify the struture of the array to change it, but that would be a kind of workaround. but generally, I'm agree with Explosion Pills, you have tools that you can use to parse that array.
Upvotes: 1
Reputation: 191749
Regular expressions are poor for parsing and working with xml
in general. PHP has very nice built-in parsers with DOMDocument
(wrapper for the awesome libxml2) and SimpleXML
.
Upvotes: 3