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!