File size: 2.53Kb
<?php
if (version_compare(PHP_VERSION,'5','>='))
{
require_once('domxml-php4-to-php5.php');
}
class Array2Xml
{
var $array;
var $xmlDoc;
function Array2Xml($array = null)
{
$this->xmlDoc = null;
$this->setArray($array);
}
function setArray($array)
{
$this->array = is_array($array) ? $array : null;
}
function getXml($formated = false)
{
if(!isset($this->xmlDoc))
{
return "";
}
else
{
return $this->xmlDoc->dump_mem($formated);
}
}
function getArray()
{
return $this->array;
}
function encode($str)
{
return iconv("windows-1251", "utf-8", $str);
}
function build($formated = false)
{
$this->xml = "";
if(!$this->array)
{
return true;
}
// Copy
$array = $this->array;
$this->xmlDoc = domxml_new_doc("1.0");
$this->xmlDoc->add_root(isset($array["root"]) ? $array["root"] : "root");
unset($array["root"]);
$this->buildNode($array, $this->xmlDoc->document_element());
return $this->xmlDoc->dump_mem($formated);
}
// Recursive
function buildNode($array, &$xmlNode)
{
if(method_exists($xmlNode, "set_attribute") && is_array($array) && isset($array["attributes"]))
{
if(is_array($array["attributes"]))
{
foreach($array["attributes"] as $name=>$value)
{
$xmlNode->set_attribute($name, $this->encode($value));
}
}
unset($array["attributes"]);
}
if(is_array($array))
{
foreach($array as $name=>$value)
{
if(strtolower($name) == "!cdata")
{
$xmlNode->append_child($this->xmlDoc->create_cdata_section($this->encode($array[$name])));
}
elseif(strtolower($name) == "text")
{
$xmlNode->append_child($this->xmlDoc->create_text_node($this->encode($array[$name])));
}
elseif(is_array($value))
{
$keys = array_keys($value);
$keysAreNumeric = true;
foreach($keys as $key)
{
if(!is_numeric($key))
{
$keysAreNumeric = false;
break;
}
}
if($keysAreNumeric)
{
foreach($value as $number=>$item)
{
$this->buildNode($array[$name][$number], $xmlNode->append_child($this->xmlDoc->create_element($name)));
}
}
else
{
$this->buildNode($array[$name], $xmlNode->append_child($this->xmlDoc->create_element($name)));
}
}
else
{
$this->buildNode($array[$name], $xmlNode->append_child($this->xmlDoc->create_element($name)));
}
}
}
elseif(is_string($array))
{
$xmlNode->append_child($this->xmlDoc->create_text_node($this->encode($array)));
}
}
}
?>