note 104792 deleted from function.xml-set-element-handler by danbrown
| From: | danbrown@php.net | Date: | Thu, 07 Jul 2011 14:43:04 +0000 |
| Subject: | note 104792 deleted from function.xml-set-element-handler by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-181325@lists.php.net to get a copy of this message | ||
Note Submitter: matthias dot pfafferodt at mapfa dot de
----
Here is my own class based on the post by lloeki. It allows multiply entities of one tag. Only error
checking is still missing ...
<?php
class xmldata
{
var $parser = NULL;
var $stack = array('root' => array());
var $depth = 0;
/**
* Set the parser.
*
* $parser: Class XML_Parser
*
* @access: public
*/
function setParser(&$parser)
{
$this->parser = &$parser;
}
/**
* Handle opening of a XML elements.
*
* $parser: Class parser class
* $name: String name of the tag
* $attrs: (Array) attributs of the tag
*
* @access: public
*/
function startHandler($parser, $name, $attrs)
{
$element = array();
foreach ($attrs as $key => $value) {
$element[XML_ATTR][strtolower($key)] = $value;
}
end($this->stack);
$k = key($this->stack);
$n = strtolower($name);
if (!isset($this->stack[$k][XML_SUB][$n])) {
$this->stack[$k][XML_SUB][$n] = &$element;
} else {
if (isset($this->stack[$k][XML_SUB][$n][XML_ATTR])) {
$tmp = $this->stack[$k][XML_SUB][$n];
unset($this->stack[$k][XML_SUB][$n]);
$this->stack[$k][XML_SUB][$n] = array();
$this->stack[$k][XML_SUB][$n][] = &$tmp;
}
$this->stack[$k][XML_SUB][$n][] = &$element;
}
$this->stack[$n] = &$element;
$this->depth++;
return TRUE;
}
/**
* Handle closing of aXML elements.
*
* $parser: Class parser class
* $name: String name of the tag
*
* @access: public
*/
function endHandler($parser, $name)
{
array_pop($this->stack);
$this->depth--;
return TRUE;
}
/**
* Handle data of an XML element.
*
* $parser: Class parser class
* $data: (Array) data for the tag
*
* @access: public
*/
function cdataHandler($parser, $data)
{
$data = trim($data);
if (empty($data)) {
return TRUE;
}
end($this->stack);
$k = key($this->stack);
$this->stack[$k][XML_DATA] = $data;
return TRUE;
}
/**
* Return the data as array.
*
* @access: public
*/
function get_result()
{
return $this->stack;
}
}
?>
example:
<?xml version='1.0' standalone='yes'?>
<test name="test">
<parameter name="string">abc</parameter>
<parameter name="int">123</parameter>
</test>
result:
Array
(
[root] => Array
(
[S] => Array
(
[test] => Array
(
[A] => Array
(
[name] => test
)
[S] => Array
(
[parameter] => Array
(
[0] => Array
(
[A] => Array
(
[name] => string
)
[D] => abc
)
[1] => Array
(
[A] => Array
(
[name] => int
)
[D] => 123
)
)
)
)
)
)
)