I have an array ($array) that looks like this:
Array
(
[0] => Array
(
[0] => A
[1] => B
[2] => C
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[2] => Array
(
[0] => apple
[1] => orange
[2] => banana
)
)
With CreateXML I want to take the array and create a XML document, but I'm having some problems. I'm using the foreach to get the first value from each array, because I want the [0]A [0]1 [0]apple to be in one element and so on.. With the code I have now it works for one element, how can I do it so I generates all the elements? Got lost in loops and just can't get it right.. Thanks for help!
public function CreateXML($array){
foreach ($array as $arr) {
$array2[] = $arr[0];
}
$xmlDoc = new DOMDocument();
$root = $xmlDoc->appendChild(
$xmlDoc->createElement("rootelement"));
$tag = $root->appendChild(
$xmlDoc->createElement("element"));
$tag->appendChild(
$xmlDoc->createElement("Letter", $array2[0]));
$tag->appendChild(
$xmlDoc->createElement("Number", $array2[1]));
$tag->appendChild(
$xmlDoc->createElement("Fruit", $array2[2]));
header("Content-Type: text/plain");
$xmlDoc->formatOutput = true;
echo $xmlDoc->saveXML();
}
$newArray = array();
for($i = 0; $i <= count($array[0]); $i++) {
$newArray[] = array($array[0][$i], $array[1][$i], $array[2][$i]);
}
// Some XML here
foreach($newArray as $row) {
$tag->appendChild(
$xmlDoc->createElement("Letter", $row[0]));
$tag->appendChild(
$xmlDoc->createElement("Number", $row[1]));
$tag->appendChild(
$xmlDoc->createElement("Fruit", $row[2]));
}
// Some more XML and output
That will work only if each of the sub arrays has exactly same number of elements
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