I'm working on an XML library, that can create / parse xml's from arrays/jsons. I managed to write the parser with xml_parser (and google help :p) cause SimpleXML wasn't good enough for what I'm doing.
I've managed to create an array that looks something like that:
Array
(
[flow] => Array
(
[math] => Array
(
[apply] => Array
(
[lt] => Array
(
)
[apply] => Array
(
[divide] => Array
(
)
[apply] => Array
(
[minus] => Array
(
)
)
)
[otherStuff] => 0
)
)
[true] => Array
(
)
[true_attr] => Array
(
[xsi:type] => SomeStuff
[id] => 2
)
)
[flow_attr] => Array
(
[id] => 0
[xmlns:xsi] => http://www.w3.org/2001/XMLSchema-instance
)
)
As you can see, it should look something like this ( not the best example :p ):
<flow id="0">
<math>
<lalaa/>
<appyl>
</apply>
</math>
</flow>
Note that empty arrays should end with /> for example , and so on
As you can see I separated the node it self to node_attr that contains the attrs of the nodes. Like flow_attr, true_attr.
Anyone have an idea how to convert this array back to xml? I'm just lost and don't know what to do.
Thanks for the help!
function recurse2xml ($array, &$string = "") {
foreach ($array as $key => $subArray) {
if (substr($key, -5) == "_attr")
continue;
$attrs = "";
if (isset($array["$key_attr"]))
foreach ($array["$key_attr"] as $attr => $value)
$attrs .= " $attr='".str_replace($value, "'", "\\'")."'";
if (empty($subArray)) {
$string .= "<$key$attrs />";
} else {
$string .= "<$key$attrs>";
if (is_scalar($subArray))
$string .= $subArray;
else
recurse2xml($subArray, $string);
$string .= "</$key>";
}
}
return $string;
}
This function called with recurse2xml($array); expands your array tree into an xml tree (string form).
Try Array2XML, worked flawlesly for me. Including CDATA Parts, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With