note 48947 rejected from function.xml-parser-create by victor
| From: | victor@php.net | Date: | Thu, 13 Jan 2005 09:26:44 +0000 |
| Subject: | note 48947 rejected from function.xml-parser-create by victor | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-83182@lists.php.net to get a copy of this message | ||
Note Submitter: Bertg at telenet dot be
----
I do use xml files with repeating nodes (or something like that), so I created a parser that will
place repeating nodes into a new array wich has a pointer with their common node-name.
example:
xml file:
<root>
<level1>
<node> value 1</node>
</level1>
<level2>
<node> value 1</node>
<node> value 2</node>
</leval2>
</root>
array:
Array
(
[ROOT] => Array
(
[LEVEL1] => Array
(
[NODE] => value 1
)
[LEVEL2] => Array
(
[NODE] => Array
(
[0] => value 1
[1] => value 2
)
)
)
)
I think this could be usefull, so here is the code.
It's probably not perfect, but you are free to use and adjust it. (and if you want, you could
let me know if you use/change it)
<?php
class XML {
function XML() {
}
function XmlToArray($data){
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $xml_values, $xml_index);
xml_parser_free($xml_parser);
$i = 0;
return $this->_XmlToArray($xml_values, '', $i);
}
function _XmlToArray($xml_values, $parent = '', &$i){
$out = array();
while ($i < count($xml_values) && $xml_values[$i]['type'] !=
'close') {
$xml_value = $xml_values[$i];
if ($xml_value['type'] == 'complete') {
$out = $this->_SetNode($xml_value['tag'], $this->_GetCompleteNode($xml_value),
$out);
} else if ($xml_value['type'] == 'open') {
$i++;
$out = $this->_SetNode($xml_value['tag'], $this->_XmlToArray($xml_values,
$xml_value['tag'], &$i), $out);
}
$parent = $xml_value['tag'];
$i++;
}
//print_r($out);
$keys = array_keys($out);
if (is_array($out[$keys[0]]) && in_array('§xmlparserIndicatorindicator',
$out[$keys[0]])){
array_shift($out[$keys[0]]);
}
return $out;
}
function _SetNode ($name, $value, $tree){
if (array_key_exists($name, $tree)){
$content = $tree[$name];
$tree[$name] = array();
if (is_array($content) && in_array('§xmlparserIndicatorindicator', $content)){
foreach ($content as $item){
array_push($tree[$name], $item);
}
} else {
array_push($tree[$name], '§xmlparserIndicatorindicator');
array_push($tree[$name], $content);
}
array_push($tree[$name], $value);
} else {
$tree[$name] = $value;
}
return $tree;
}
function _GetCompleteNode ($nodeInfo){
$out = '';
if (isset($nodeInfo['value'])){
$out = $nodeInfo['value'];
}
return $out;
}
}
?>