note 57961 deleted from function.xml-parse-into-struct by sniper
| From: | sniper@php.net | Date: | Mon, 28 Nov 2005 13:08:58 +0000 |
| Subject: | note 57961 deleted from function.xml-parse-into-struct by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-99238@lists.php.net to get a copy of this message | ||
Note Submitter: kieran at kieran dot ca
----
Here's a recursive function that works for me... I prefer this array structure for xml data.
Cheers, Kieran
<?
/*
|
| _xml2array - another abstraction layer on xml_parse_into_struct
| that returns a nice nested array.
|
| @param: $xml is a string containing a full xml document
|
| returns: a nested php array that looks like this:
|
| array
| (
| [_name] => the name of the tag
| [_attributes] => an array of 'attribute'=>'value'
combos
| [_value] => the text contents of the node
| [_children] => an array of these arrays, one for each child node.
| )
|
| notes: thanks to 'jeffg at activestate dot com' who inspired
| me to essentially re-write his example code from php.net
|
| me: Kieran Huggins < kieran[at]kieran[dot]ca >
|
*/
function _xml2array($xml){
if(!is_array($xml)){
$raw_xml = $xml;
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($xml_parser, $raw_xml, $xml);
xml_parser_free($xml_parser);
}
$array['_name'] = $xml[0]['tag'];
if($xml[0]['attributes']){
$array['_attributes'] = $xml[0]['attributes'];
}
if($xml[0]['value']){
$array['_value'] = $xml[0]['value'];
}
switch($xml[0]['type']){
case 'open':// there are children - go deeper
while($xml[1]['level'] > $xml[0]['level']){
array_shift($xml);
$array['_children'][]=_xml2array($xml);
}
break;
default:
array_shift($xml);
}
return $array;
}
?>