krot

xml_to_array

Jul 29th, 2016
84
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function xml_to_array($xml){//0JDQstGC0L7RgDoKSUNROjU1NTc3Nzk4MyBza3lwZTphb2xucDE=
  2.   $parser = xml_parser_create();
  3.   xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  4.   xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  5.   xml_parse_into_struct($parser, $xml, $tags);
  6.   xml_parser_free($parser);
  7.     $elements=array();
  8.     $uk=&$elements;
  9.       foreach ($tags as $tag) {
  10.           if ($tag['type'] == "complete" || $tag['type'] == "open"){
  11.             if(($tag['type'] == "complete")||($tag['value'])){
  12.             $uk[$tag['tag']][]=$tag['value'];
  13.             }
  14.             if ($tag['type'] == "open"){
  15.             $parent[$tag['level']]=&$uk;
  16.             $uk=&$uk[$tag['tag']];}
  17.           }
  18.           if ($tag['type'] == "close"){
  19.       $uk=&$parent[$tag['level']];
  20.     }
  21. }
  22. return $elements;
  23. }
  24. //2 v
  25. function xml_to_array($xml) {
  26.           $parser = xml_parser_create();
  27.           xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  28.           xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  29.           xml_parse_into_struct($parser, $xml, $tags);
  30.           xml_parser_free($parser);
  31.           $elements = array();  // the currently filling [child] XmlElement array
  32.           $stack = array();
  33.           foreach ($tags as $tag) {
  34.             $index = count($elements);
  35.             if ($tag['type'] == "complete" || $tag['type'] == "open") {
  36.               $elements[$index]['name'] = $tag['tag'];
  37.               if(isset($tag['attributes']))$elements[$index]['attributes'] = $tag['attributes'];
  38.               if(isset($tag['value']))$elements[$index]['content'] = $tag['value'];
  39.              
  40.               if ($tag['type'] == "open") {  // push
  41.                 $elements[$index]['children'] = array();
  42.                 $stack[count($stack)] = &$elements;
  43.                 $elements = &$elements[$index]['children'];
  44.               }
  45.             }
  46.             if ($tag['type'] == "close") {  // pop
  47.               $elements = &$stack[count($stack) - 1];
  48.               unset($stack[count($stack) - 1]);
  49.             }
  50.           }
  51.          
  52.           return $elements;  // the single top-level element
  53.         }
  54. //3
  55. $xml = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
  56. $json = json_encode($xml);
  57. $array = json_decode($json,TRUE);
RAW Paste Data