*/
/*
TXML is a class that provides a REALLY SIMPLISTIC transformation from an XML to Array and vice versa.
TXML DOES NOT
- handle attributes at all.
- can not detect ALL ambiguous child nodes without some help, but does a good job of detecting most
Once again, this class provides a quick method of using data within XML, but the simple implementation
does not expose all the power of XML.
If you wish to use that power, the family of DOM XML classes are a better fit for your needs.
However, it is very rare that one needs to use all these advanced features of XML, in which case TXML
will be a very nice solution to use.
*/
class TXML
{
private $doc = null;
private $xml_version = '1.0';
private $xml_encoding = 'iso-8859-1';
private $ambiguous_children = array(); //Note: Not yet fully implemented. No interface to add items to this list
/* TODO: Potential future improvements
public $skipemtyvalues = false; //Do not create nodes if values for node are empty
public $keycase = "none|upper|lower"; //Transform all keys to lower or upper case, or leave "as-is"
*/
/*
Class Constructor
The $xml parameter can be
$xml=null or not provided, do nothing
$xml=string, load XML string into DOM
$xml=array, parse array into DOM
Usage:
$xml = new TXML();
$xmlstr = $xml->ArrayToXML($array);
$xml = new TXML("my value");
$a = $xml->AsArray();
$a = array();
$a["xml"]["value"] = "my value";
$xml = new TXML($a);
$xmlstr = $xml->AsString();
*/
function __construct($xml = null)
{
if(!is_null($xml))
{
//If we get an array, lets parse it into the DOM
if(is_array($xml))
$this->ArrayToDOM($xml);
else if(is_string($xml))
$this->open($xml);
}
}
//Open DOM document, optionally loading it with a raw XML sheet
private function open($xml = null)
{
$this->close();
$this->doc = new DOMDocument($this->xml_version, $this->xml_encoding);
if(!is_null($xml) && is_string($xml)) $this->doc->LoadXML($xml);
}
//Close XML Document and disposes of any memory used
private function close()
{
if($this->doc!=null)
{
$this->doc=null;
}
}
//############################################################
// XML to Array section (Private helper functions)
//############################################################
/*
Function to check if Parent name is a plural of Child name
Note: Right now the function only checks for
[name]s = [name], i.e. rows is plural of row
[name]es = [name], i.e. benches is plural of bench
[name]list = [name], i.e. not really a plural, but collection identifier
Special cases:
[name][f]ves = [name][f], i.e. calves is plural of calf
[name][y]ies = [name][y], i.e. babies is plural of baby
children is plural of child
We thus only check the most common cases in plurals.
Extreme cases like Feet->Foot, platypi->platypus are not supported.
Resource: http://en.wikipedia.org/wiki/English_plural
*/
private function IsPlural($parent_name, $child_name)
{
$parent_name = strtolower($parent_name);
$child_name = strtolower($child_name);
//Easy Suffix plurals
$plurals = array("s","es","list");
foreach($plurals as $plural)
if($parent_name==$child_name.$plural) return true;
//Special plurals
if($parent_name=="children" && $child_name=="child") return true;
$lastchar = substr($child_name,strlen($child_name)-1,1);
//Calves->Calf, Hooves->Hoof
if(($lastchar=="f") && (substr($child_name,0,strlen($child_name)-1)."ves")==$parent_name) return true;
//babies->baby, ladies->lady
if(($lastchar=="y") && (substr($child_name,0,strlen($child_name)-1)."ies")==$parent_name) return true;
return false;
}
//Internal function used to parse a DOM XML tree into a simple array
private function DOMToArray($domnode, &$array)
{
$array_ptr = &$array;
$domnode = $domnode->firstChild;
while (!is_null($domnode))
{
if (!(trim($domnode->nodeValue) == ""))
{
switch ($domnode->nodeType)
{
case XML_TEXT_NODE:
{
$array_ptr = $domnode->nodeValue;
break;
}
case XML_ELEMENT_NODE:
{
$array_ptr = &$array[$domnode->nodeName];
break;
}
}
//Run through all child nodes in an attemot to automatically detect children lists
if ($domnode->hasChildNodes() )
{
//Check1: Are we working with siblings of the same name?
$mynode = $domnode->firstChild;
$namecount = array(); $childrenlist = false; $childcount=0;
while(!is_null($mynode))
{
$childcount++;
$namecount[$mynode->nodeName]++;
//If any node exists more than once, we ASSUME it must be part of a children list
if(!$childrenlist && $namecount[$mynode->nodeName]>1) $childrenlist = true;
//If any node is in our ambiguous child list, we automatically ASSUME it must be part of a children list
//Ambiguous childs are rows that can have 0, 1 or more rows. Without this detection, 1 row "lists" can not be properly detected
if(!$childrenlist && $this->ambiguous_children[$mynode->nodeName]) $childrenlist = true;
//If any node matches the parent where the parent is the plural form of the child, we ASSUME it must be part of a children list
//Note: Currently we only handle the very simple case of "S" being added to the end of the list
if(!$childrenlist && $this->IsPlural($domnode->nodeName, $mynode->nodeName)) $childrenlist = true;
$mynode = $mynode->nextSibling;
}
//Warn if we do not have a properly formatted XML sheet (At least properly formed for our simple parser)
if($childrenlist && (count($namecount)>1))
throw new Exception("TXML.DOMToArray: XML contains multiple node names on the same level combined with duplicate names for some node levels. This XML parser is unable to handle this structure.");
//Build array for each child node
if($childrenlist)
{
$mynode = $domnode->firstChild;
while(!is_null($mynode))
{
$my_array_ptr = &$array_ptr[$mynode->nodeName][];
$this->DOMToArray($mynode, $my_array_ptr);
$mynode = $mynode->nextSibling;
}
}
//else just add XML node to array structure
else $this->DOMToArray($domnode, $array_ptr);
}
}
$domnode = $domnode->nextSibling;
}
}
//Internal helper function used in process when converting DOM XML tree to simple Array
//Checks if node is valid, if not - create a valid node on XML document root
//Otherwise add node to bottom of current root node
private function Node_Add(&$newnode, &$rootnode)
{
if($rootnode==null)
$mynode = $this->doc->appendChild($newnode);
else
$mynode = $rootnode->appendChild($newnode);
return $mynode;
}
//############################################################
// Array to XML section (Private helper functions)
//############################################################
//Checks if data contains numeric keys - in which case we assume it contains a list of children
//Note: We can safely assume this as numeric keys are invalid in XML
private function ChildKeyIsNum(&$data)
{
if(!is_array($data)) return false;
reset($data);
list($key, $value) = each($data);
if(is_numeric($key))
return true;
else
return false;
}
//Builds XML tree from array
private function BuildXMLTree(&$data, $rootnode = null)
{
if(is_array($data))
{
foreach($data as $key => $val)
{
//Check if node contains list of child nodes
if($this->ChildKeyIsNum($val))
{
foreach($val as $k => $v)
{
$mynode = $this->doc->createElement($key);
$childnode = $this->Node_Add($mynode, $rootnode);
$this->BuildXMLTree($v, $childnode);
}
}
else
{
$mynode = $this->doc->createElement($key);
$this->Node_Add($mynode, $rootnode);
$this->BuildXMLTree($val, $mynode);
}
}
}
else
{
$mynode = $this->doc->createTextNode($data);
$this->Node_Add($mynode, $rootnode);
}
}
//############################################################
// Public TXML functions
//############################################################
//Convert DOM XML Tree into XML string
/*
Usage:
$a["xml"]["test"] = "test value";
$x = new TXML();
$x->ArrayToDOM($a);
echo "".htmlentities($x->AsString())."
";
*/
public function AsString()
{
return $this->doc->saveXML();
}
//Convert DOM XML Tree into Simple Array structure
/*
Usage:
$xmlstr = 'test value';
$x = new TXML($xmlstr);
var_dump($x->AsArray());
*/
public function AsArray()
{
$array = array();
$this->DOMToArray($this->doc, $array);
return $array;
}
//Parse Array into simple XML tree
/*
Usage:
$a["xml"]["test"] = "test value";
$x = new TXML();
$x->ArrayToDOM($a);
$x->echoXML();
*/
public function ArrayToDOM(&$data)
{
$this->open(); //Open/Create DOM document
$this->BuildXMLTree($data, null);
}
//Convert Array to an XML string
/*
Usage:
$a["xml"]["test"] = "test value";
$x = new TXML();
$xmlstr = $x->ArrayToXML($a);
echo "".htmlentities($xmlstr)."
";
*/
public function ArrayToXML(&$data)
{
$this->ArrayToDOM($data);
return $this->AsString();
}
/*
Usage:
$xmlstr = 'test value';
$x = new TXML();
$a = $x->XMLToArray($xmlstr);
var_dump($a);
*/
public function XMLToArray(&$xml)
{
$this->open($xml); //Open/Create DOM document
return $this->AsArray();
}
//Outputs the proper MIME header for use when displaying XML data
//Rarely used on its own, usually used within TXML::echoXML()
public function XMLheader()
{
header("Content-type: text/xml");
}
//$xml can be either an array or string (or null, in which case the interal DOM structure is used)
//If $xml is an array it is first converted to an XML string
//This function then sets the proper MIME type header (text/xml) and outputs the XML string
public function echoXML($xml = null)
{
if(is_null($xml))
$xml = $this->AsString();
else if(is_array($xml))
$xml = $this->ArrayToXML($xml);
$this->XMLheader();
echo $xml;
}
}
//#############################################################
// Global functions for quick access to most common used tasks
//#############################################################
//Alias for TXML::ArrayToXML($xml), just saves you the step of creating the TXML object
function ArrayToXML($xml)
{
$x = new TXML();
return $x->ArrayToXML($xml);
}
//Alias for ArrayToXML($xml)
function Arr2XML($xml)
{
$x = new TXML();
return $x->ArrayToXML($xml);
}
//Alias for TXML::XMLToArray($xml), just saves you the step of creating the TXML object
function XMLToArray($xml)
{
$x = new TXML();
return $x->XMLToArray($xml);
}
//Alias for TXML::echoXML($xml), just saves you the step of creating the TXML object
function echoXML($xml)
{
$x = new TXML();
$x->echoXML($xml);
}
/*
$xmlstr = 'test value1';
$x = new TXML();
$a = $x->XMLToArray($xmlstr);
var_dump($a);
Exit;
*/
?>