2

So I'm trying to convert an array to an XML document (just outputting it as a string). I know php has json_encode built in and it works fine, but I can't seem to find any good XML equivalents.

Basically, the array is the result of a PDOStatement->fetchAll();

I'd like the output to look like this:

<arrayitem>
   <iteminfo1>text</iteminfo1>
   <iteminfo2>text</iteminfo2>
   <iteminfo3>text</iteminfo3>
   <iteminfo4>text</iteminfo4>
   <iteminfo5>text</iteminfo5>
</arrayitem>
0

3 Answers 3

1

Taken straight off of PHP: SimpleXML - Manual

function array2XML($arr,$root) { 
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><{$root}></{$root}>");
$f = create_function('$f,$c,$a',' 
    foreach($a as $v) { 
        if(isset($v["@text"])) { 
            $ch = $c->addChild($v["@tag"],$v["@text"]); 
        } else { 
            $ch = $c->addChild($v["@tag"]); 
            if(isset($v["@items"])) { 
                $f($f,$ch,$v["@items"]); 
            } 
        } 
        if(isset($v["@attr"])) { 
            foreach($v["@attr"] as $attr => $val) { 
                $ch->addAttribute($attr,$val); 
            } 
        } 
    }'); 
$f($f,$xml,$arr); 
return $xml->asXML(); 
} 
Sign up to request clarification or add additional context in comments.

Comments

0

There is no built-in tools to do that, but it is easy to implement.

Comments

0

There is a built in library that can help you do this, but not as simple as json_encode.

http://php.net/manual/en/book.simplexml.php

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.