Iterating arrays and DOM
Posted: Wed May 28, 2008 6:26 pm
Just to clear this up I had an old topic that was asking how to write XML but now that I have a written class and am having problems traversing an array I've decided to make a new topic.
Anyways, essentially I'm trying to iterate through an array of array's (I'm assuming there can be an infinite number of arrays) and create a DOM/XML structure that represents the array in the data. Here's the current class I've written:
Here is the code I'm using to test this class:
And then the output:
For the most part it's working, but there's one minor problem. As seen in the XML above somehow the quest2 is getting nested in quest1 when it shouldn't be. From what I understand after it finishes looping through quest1 it's not going back up in the hierarchy (as it should be) but continuing onto quest2 and including it in quest1. I realize this is my fault in the code, but I'm not sure how to go about fixing it.
Any help would be greatly appreciated (since this aspect of the project is due soon). Thanks!
Anyways, essentially I'm trying to iterate through an array of array's (I'm assuming there can be an infinite number of arrays) and create a DOM/XML structure that represents the array in the data. Here's the current class I've written:
Code: Select all
<?php
class XMLGen
{
private $data;
private $xml;
private $lastEle;
function __construct($data)
{
$this->data = $data;
}
public function toXML()
{
$this->xml = new DOMDocument('1.0', 'UTF-8');
$root = $this->xml->createElement("results");
$this->lastEle = $root;
$this->iterate($this->data);
$this->xml->appendChild($root);
return $this->xml->saveXML();
}
private function iterate($array)
{
foreach($array as $key => $value)
{
print_r($array);
if (is_numeric($key)) { continue; }
if (is_array($value))
{
$ele = $this->xml->createElement($key);
$this->lastEle->appendChild($ele);
$this->lastEle = $ele;
$this->iterate($value);
} else {
$this->lastEle->appendChild($this->xml->createElement($key, $value));
}
}
}
}
?>Code: Select all
$data = array("quests" => array("quest1" => array("name" => "test", "id" => "1"), "quest2" => array("name" => "test2", "id" => "2")));
$gen = new XMLGen($data);
echo $gen->toXML();Code: Select all
<results><quests><quest1><name>test</name><id>1</id><quest2><name>test2</name><id>2</id></quest2></quest1></quests></results>Any help would be greatly appreciated (since this aspect of the project is due soon). Thanks!