1k visitas
Parse XML to array in PHP
This is the best function I have found to parse XML and save it as an associative array. I found it in the official PHP documentation: PHP: xml_parse
PHP
- <?php
- function xml2array($url, $get_attributes = 1, $priority = 'tag')
- {
- $contents = "";
- {
- }
- {
- }
- {
- }
- if (!$xml_values)
- return; //Hmm...
- $current = & $xml_array;
- foreach ($xml_values as $data)
- {
- {
- if ($priority == 'tag')
- $result = $value;
- else
- $result['value'] = $value;
- }
- {
- foreach ($attributes as $attr => $val)
- {
- if ($priority == 'tag')
- $attributes_data[$attr] = $val;
- else
- $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
- }
- }
- if ($type == "open")
- {
- $parent[$level -1] = & $current;
- {
- $current[$tag] = $result;
- if ($attributes_data)
- $current[$tag . '_attr'] = $attributes_data;
- $repeated_tag_index[$tag . '_' . $level] = 1;
- $current = & $current[$tag];
- }
- else
- {
- {
- $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
- $repeated_tag_index[$tag . '_' . $level]++;
- }
- else
- {
- $current[$tag],
- $result
- );
- $repeated_tag_index[$tag . '_' . $level] = 2;
- {
- $current[$tag]['0_attr'] = $current[$tag . '_attr'];
- }
- }
- $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
- $current = & $current[$tag][$last_item_index];
- }
- }
- elseif ($type == "complete")
- {
- {
- $current[$tag] = $result;
- $repeated_tag_index[$tag . '_' . $level] = 1;
- if ($priority == 'tag' and $attributes_data)
- $current[$tag . '_attr'] = $attributes_data;
- }
- else
- {
- {
- $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
- if ($priority == 'tag' and $get_attributes and $attributes_data)
- {
- $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
- }
- $repeated_tag_index[$tag . '_' . $level]++;
- }
- else
- {
- $current[$tag],
- $result
- );
- $repeated_tag_index[$tag . '_' . $level] = 1;
- if ($priority == 'tag' and $get_attributes)
- {
- {
- $current[$tag]['0_attr'] = $current[$tag . '_attr'];
- }
- if ($attributes_data)
- {
- $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
- }
- }
- $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
- }
- }
- }
- elseif ($type == 'close')
- {
- $current = & $parent[$level -1];
- }
- }
- return ($xml_array);
- }
- ?>
Enviado por miguelSantirso hace over 2 years — modificado por última vez hace less than a minute