0

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.

2
  • 1
    You can convert json to XML with PEAR::XML_Serializer. Firstly, convert json to an object then convert the object to XML Commented Jun 30, 2012 at 17:25
  • the function should be correctly linked... Commented Jun 30, 2012 at 17:30

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

SimpleXML is definitely the way to go if you've never used either of these before.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.