note 90732 added to function.xml-parse
| From: | vladimir_wof_nikolaich_dot_ru at osu1 dot php dot net | Date: | Thu, 07 May 2009 05:34:51 +0000 |
| Subject: | note 90732 added to function.xml-parse | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-154296@lists.php.net to get a copy of this message | ||
Function that posted by "lz_speedy at web dot de" is nice, but have some problems with
attributes in open tags, so
I hope this function will be helpful for others:
function my_xml2array($__url)
{
$xml_values = array();
$contents = file_get_contents($__url);
$parser = xml_parser_create('');
if(!$parser)
return false;
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);
xml_parse_into_struct($parser, trim($contents), $xml_values);
xml_parser_free($parser);
if (!$xml_values)
return array();
$xml_array = array();
$last_tag_ar =& $xml_array;
$parents = array();
foreach ($xml_values as $data)
{
switch($data['type'])
{
case 'open':
$new_tag = array('name' => $data['tag']);
if(isset($data['attributes']))
$new_tag['attributes'] = $data['attributes'];
if(isset($data['value']) && trim($data['value']))
$new_tag['value'] = trim($data['value']);
$last_tag_ar[] = $new_tag;
$parents[$data['level']] =& $last_tag_ar;
$last_tag_ar =& $last_tag_ar[count($last_tag_ar)-1];
break;
case 'complete':
$new_tag = array('name' => $data['tag']);
if(isset($data['attributes']))
$new_tag['attributes'] = $data['attributes'];
if(isset($data['value']) && trim($data['value']))
$new_tag['value'] = trim($data['value']);
$last_count = count($last_tag_ar)-1;
// there can be a situation, where $last_count == -1, so we just check it
// (in the case of open tag we always add a value by ourself before so we can't get such a
value)
$last_tag_ar[$last_count>=0 ? $last_count : 0][] = $new_tag;
break;
case 'close':
$last_tag_ar =& $parents[$data['level']];
break;
default:
break;
};
}
return $xml_array;
}
----
Server IP: 69.147.83.197
Probable Submitter: 62.231.13.130 (proxied: 127.0.0.1)
----
Manual Page -- http://www.php.net/manual/en/function.xml-parse.php
Edit -- https://master.php.net/note/edit/90732
Del: integrated -- https://master.php.net/note/delete/90732/integrated
Del: useless -- https://master.php.net/note/delete/90732/useless
Del: bad code -- https://master.php.net/note/delete/90732/bad+code
Del: spam -- https://master.php.net/note/delete/90732/spam
Del: non-english -- https://master.php.net/note/delete/90732/non-english
Del: in docs -- https://master.php.net/note/delete/90732/in+docs
Del: other reasons-- https://master.php.net/note/delete/90732
Reject -- https://master.php.net/note/reject/90732
Search -- https://master.php.net/manage/user-notes.php