How to convert xml into array in php?

前端 未结 9 1498
半阙折子戏
半阙折子戏 2020-11-22 02:54

I want to convert below XML to PHP array. Any suggestions on how I can do this?


   
     
       

        
9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 03:18

    See https://github.com/gaarf/XML-string-to-PHP-array/blob/master/xmlstr_to_array.php

    loadXML($xmlstr);
      $root = $doc->documentElement;
      $output = domnode_to_array($root);
      $output['@root'] = $root->tagName;
      return $output;
    }
    function domnode_to_array($node) {
      $output = array();
      switch ($node->nodeType) {
        case XML_CDATA_SECTION_NODE:
        case XML_TEXT_NODE:
          $output = trim($node->textContent);
        break;
        case XML_ELEMENT_NODE:
          for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
            $child = $node->childNodes->item($i);
            $v = domnode_to_array($child);
            if(isset($child->tagName)) {
              $t = $child->tagName;
              if(!isset($output[$t])) {
                $output[$t] = array();
              }
              $output[$t][] = $v;
            }
            elseif($v || $v === '0') {
              $output = (string) $v;
            }
          }
          if($node->attributes->length && !is_array($output)) { //Has attributes but isn't an array
            $output = array('@content'=>$output); //Change output into an array.
          }
          if(is_array($output)) {
            if($node->attributes->length) {
              $a = array();
              foreach($node->attributes as $attrName => $attrNode) {
                $a[$attrName] = (string) $attrNode->value;
              }
              $output['@attributes'] = $a;
            }
            foreach ($output as $t => $v) {
              if(is_array($v) && count($v)==1 && $t!='@attributes') {
                $output[$t] = $v[0];
              }
            }
          }
        break;
      }
      return $output;
    }
    

提交回复
热议问题