note 71546 deleted from function.xml-parse-into-struct by bjori
| From: | bjori@php.net | Date: | Tue, 05 Dec 2006 15:08:52 +0000 |
| Subject: | note 71546 deleted from function.xml-parse-into-struct by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-120305@lists.php.net to get a copy of this message | ||
Note Submitter: Predrag Supurovic
Reason: this isnt script library
----
I have this XML structure which does not parse to array well, using given examples:
<?xml version="1.0" ?>
<_data>
<header>
<document>test</document>
<source>source_Data</source>
<file_path>path_to_file</file_path>
<last_change>changed</last_change>
<charset>codepage</charset>
</header>
<data>
<n0001>
<id>0001</id>
<type>U</type>
<caption>Record 1</caption>
</n0001>
<n0002>
<id>0002</id>
<type>M</type>
<caption>Record 2</caption>
<subdata>
<data1>d1</data1>
<data2>d2</data2>
<data3>d3</data3>
</subdata>
</n0002>
<n0003>
<id>0003</id>
<type>K</type>
<caption>Record 3</caption>
</n0003>
</data>
</_data>
I wrote new function which does the job:
<?php
function xml2array ($p_xmlstrng) {
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $p_xmlstrng, $vals, $index);
xml_parser_free($xml_parser);
$data = Array ();
$path[0] = &$data;
foreach ($vals as $item) {
$item_level = $item['level'];
$item_tag = $item['tag'];
$item_type = $item['type'];
$path[$item_level] = &$path[$item_level-1][$item_tag];
switch ($item_type) {
case 'open' :
$path[$item_level] = '';
break;
case 'complete' :
if (isset ($item['value'])) {
$path[$item_level] = $item['value'];
} else {
$path[$item_level] = '';
}
break;
} // switch
} // foreach
return $data;
}
?>