note 106330 deleted from function.xml-parse by danbrown
| From: | danbrown@php.net | Date: | Fri, 28 Oct 2011 15:03:50 +0000 |
| Subject: | note 106330 deleted from function.xml-parse by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-184195@lists.php.net to get a copy of this message | ||
Note Submitter: derek at gmail dot com
----
A recursive way of getting a tree style array from a XML.
(same array like 'lz_speedy at web dot de 30-Dec-2008 06:20' using recursive method)
<?php
/**
* Mg_Parser_Xml_String class.
*
* Parse a xml string into a tree style array.
*
* @author Derek
*/
class Mg_Parser_Xml_String implements Mg_Parser_Interface
{
protected $_currentLevel = 1;
protected $_currentNode = null;
public function __construct()
{
}
public function parse($xmlStr)
{
$parser = xml_parser_create('');
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
if (!xml_parse_into_struct($parser, $xmlStr, $xmlValues))
{
return false;
}
xml_parser_free($parser);
if (!$xmlValues)
{
return false;
}
return $this->reformat($xmlValues);
}
/**
* Recursively reformat array into tree structure.
*
* @param type $xmlValues
* @return type
*/
public function reformat($xmlValues)
{
$result = array();
$children = array();
foreach ($xmlValues as $unit)
{
if ($unit['type'] == 'open' && $this->_currentLevel ==
$unit['level'])
{
$this->_currentNode = $unit['tag'];
}
elseif ($unit['type'] == 'close' && $unit['tag']
== $this->_currentNode)
{
$this->_currentLevel++;
$result[$this->_currentNode] = $this->reformat($children);
$this->_currentLevel--;
$children = array();
}
elseif ($unit['type'] == 'complete' &&
$this->_currentLevel == $unit['level'])
{
$result[$unit['tag']]['value'] = $unit['value'];
if (isset($unit['attributes']))
{
$result[$unit['tag']]['attributes'] =
$unit['attributes'];
}
}
else
{
$children[] = $unit;
}
}
return $result;
}
}
?>