XML Transform Array

Source: Internet
Author: User
Tags foreach php tutorial tag name xml parser
The code is as follows Copy Code

Call method
$array = Xml2array (file_get_contents (' Feed.xml ', 1, ' attribute '));
*/
function Xml2array ($contents, $get _attributes=1, $priority = ' tag ') {
if (! $contents) return array ();

if (!function_exists (' xml_parser_create ')) {
Print "' xml_parser_create () ' function not found! ';
return Array ();
}

Get the XML parser of PHP Tutorial-PHP must have this module for the parser to work
$parser = Xml_parser_create (");
Xml_parser_set_option ($parser, xml_option_target_encoding, "utf-8"); # Http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
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;//hmm ...

Initializations
$xml _array = Array ();
$parents = Array ();
$opened _tags = Array ();
$arr = Array ();

$current = & $xml _array; Refference

Go through the tags.
$repeated _tag_index = Array ();//multiple tags with same name'll be turned to an array
foreach ($xml _values as $data) {
Unset ($attributes, $value);//remove existing values, or there'll be trouble

This command would extract these variables into the foreach scope
Tag (string), type (string), level (int), attributes (array).
Extract ($data);//we could use the array by itself, but this cooler.

$result = Array ();
$attributes _data = Array ();

        if (isset ($value)) {
             if ($priority = = ' Tag ') $result = $value;
            Else $result [' value '] = $value;//put the Value in a assoc array if we are in the ' attribute ' mode
       }

       //set the attributes too.
        if (Isset ($attributes) and $get _attributes) {
             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 '
            }
       }

       //see Tag status and do the needed.
        if ($type = = "Open") {//the starting of the tag ' <tag> '
&NBSP;&N bsp;          $parent [$level-1] = & $current;
            if (!is_array ($current) or!in_array ($tag, Array_keys ($current))) {//insert new tag
                 $current [$tag] = $result;
                if ($attributes _ Data) $current [$tag. ' _attr '] = $attributes _data;
                $repeated _tag_ index[$tag. ' _ '. $level] = 1;

$current = & $current [$tag];

else {//there is another element with the same tag name

if (Isset ($current [$tag][0])) {//if There is a 0th element it's already an array


$current [$tag] [$repeated _tag_index[$tag. ' _ '. $level]] = $result;


$repeated _tag_index[$tag. ' _ '. $level]++;


else {//this section'll make the value of an array if multiple tags with the same name appear together


$current [$tag] = Array ($current [$tag], $result);//this'll combine the existing item and the new item together to Array


$repeated _tag_index[$tag. ' _ '. $level] = 2;

                     if (isset $current [$tag.] _attr ']) {//the attribute of the last (0th) tag must is moved as OK
         ;                $current [$tag] [' 0_ attr '] = $current [$tag. _attr '];
                         unset ($current [$tag.] _attr ']);
                    }

               }
                $last _item_index = $repeated _tag_index[$tag. ' _ '. $level]-1;
                $current = &$ current[$tag] [$last _item_index];
           }

       } elseif ($type = = "complete") {//tags, ends in 1 line ' <tag/> '            //see If the key is already taken.
            if (!isset ($current [$tag])) {//new key
                $current [$tag] = $ Result
                $repeated _tag_ index[$tag. ' _ '. $level] = 1;
                if ($priority = = ' Tag ' and $attributes _data) $current [$tag. ' _attr '] = $attributes _data;

else {//if taken, put all things inside a list (array)
if (Isset ($current [$tag][0]) and Is_array ($current [$tag])) {//if It is already an array ...

... push the new element into the. Array.
$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 {//if It is not An array ...
                     $current [$tag] = Array ($current [$tag], $result); . Make it an array using using the existing value and the new value
         ;            $repeated _tag_index[$tag. ' _ '. $level] = 1;
                     if ($priority = = ' Tag ' and $get _attributes) {
         & nbsp;              if (isset ($current [$tag. ') _attr ']) {//the attribute of the last (0th) tag must is moved as OK

$current [$tag] [' 0_attr '] = $current [$tag.] _attr '];
Unset ($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 ') {//end of tag ' </tag> '
$current = & $parent [$level-1];
}
}

Return ($xml _array);
}

#########################################################################################################

Class Parserxml
{
function Parserxml ()
{

}


function Parserxmlbyurl ($url)


{


$fp = @fopen ($url, ' R ');


if (! $fp) {


return 1;


}


$xmlstr = Fread ($fp, 1024);


@fclose ($FP);


if ($xmlstr = = False) {


return 0;


}


return $this-&gt;getxmltree ($XMLSTR);


}


function Getxmltree ($xmldata)


{


Ini_set (' track_errors ', ' 1 ');


$xmlreaderror = false;


$parser = Xml_parser_create ();


Xml_parser_set_option ($parser, Xml_option_skip_white, 1);


Xml_parser_set_option ($parser, xml_option_case_folding, 0);


if (!xml_parse_into_struct ($parser, $xmldata, $vals, $index)) {


$xmlreaderror = true;


return 0;


}


Xml_parser_free ($parser);

if (! $xmlreaderror) {


$result = Array ();


$i = 0;


if (Isset ($vals [$i] [' attributes ']) {


foreach (Array_keys ($vals [$i] [' attributes ']) as $attkey)


$attributes [$attkey] = $vals [$i] [' attributes '] [$attkey];


}


$result [$vals [$i] [' tag ']] = array_merge (array) $attributes, $this-&gt;getchildren ($vals, $i, ' open '));


}


Ini_set (' track_errors ', ' 0 ');


return $result;


}


function GetChildren ($vals, &amp; $i, $type)


{


if ($type = = ' complete ') {


if (Isset ($vals [$i] [' value '])


Return ($vals [$i] [' value ']);


Else


Return ";


}


$children = Array ();


while ($vals [+ + $i] [' type ']!= ' close ') {


$type = $vals [$i] [' type '];


if (Isset ($children [$vals [$i] [' tag ']]) {


if (Is_array ($children [$vals [$i] [' tag ']]) {


$temp = Array_keys ($children [$vals [$i] [' tag ']]);


if (is_string ($temp [0])) {


$a = $children [$vals [$i] [' tag ']];


Unset ($children [$vals [$i] [' tag ']]);


$children [$vals [$i] [' tag ']][0] = $a;


}


} else {


$a = $children [$vals [$i] [' tag ']];


Unset ($children [$vals [$i] [' tag ']]);


$children [$vals [$i] [' tag ']][0] = $a;


}

$children [$vals [$i] [' tag ']][] = $this-&gt;getchildren ($vals, $i, $type);


} else


$children [$vals [$i] [' tag ']] = $this-&gt;getchildren ($vals, $i, $type);


if (Isset ($vals [$i] [' attributes ']) {


$attributes = Array ();


foreach (Array_keys ($vals [$i] [' attributes ']) as $attkey)


$attributes [$attkey] = $vals [$i] [' attributes '] [$attkey];


if (Isset ($children [$vals [$i] [' tag ']]) {


if ($children [$vals [$i] [' tag ']] = = ') {


Unset ($children [$vals [$i] [' tag ']]);


$children [$vals [$i] [' tag ']] = $attributes;


}


ElseIf (Is_array ($children [$vals [$i] [' tag ']]) {


$index = count ($children [$vals [$i] [' tag ']])-1;


if ($children [$vals [$i] [' tag ']][$index] = = ') {


Unset ($children [$vals [$i] [' tag ']][$index]);


$children [$vals [$i] [' tag ']][$index] = $attributes;


}


$children [$vals [$i] [' tag ']][$index] = Array_merge ($children [$vals [$i] [' tag ']][$index], $attributes);


} else {


$value = $children [$vals [$i] [' tag ']];


Unset ($children [$vals [$i] [' tag ']]);


$children [$vals [$i] [' tag ']][' value '] = $value;


$children [$vals [$i] [' tag ']] = Array_merge ($children [$vals [$i] [' tag ']], $attributes);


}


} else


$children [$vals [$i] [' tag ']] = $attributes;


}


}


return $children;

?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.