Reputation: 2123
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>
Upvotes: 2
Views: 842
Reputation: 13517
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();
}
Upvotes: 1
Reputation: 4422
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
Upvotes: 0
Reputation: 254926
There is no built-in tools to do that, but it is easy to implement.
Upvotes: 0