PHP: Using simplexml to loop through all levels of an XML file

后端 未结 3 630
野的像风
野的像风 2021-01-03 05:16

I have a function which uses simplexml to return the first level of nodes in an XML file and write it into an unordered list:

function printAssetMap() {
             


        
3条回答
  •  盖世英雄少女心
    2021-01-03 05:48

    you need to use a recursive function. here is an example that outputs an array from XML. It is from the PHP docs - http://www.php.net/manual/en/ref.simplexml.php. You can amend this to output a list.

    children(); 
        $return = null; 
      } 
    
      foreach ($children as $element => $value) { 
        if ($value instanceof SimpleXMLElement) { 
          $values = (array)$value->children(); 
    
          if (count($values) > 0) { 
            $return[$element] = XMLToArray($value); 
          } else { 
            if (!isset($return[$element])) { 
              $return[$element] = (string)$value; 
            } else { 
              if (!is_array($return[$element])) { 
                $return[$element] = array($return[$element], (string)$value); 
              } else { 
                $return[$element][] = (string)$value; 
              } 
            } 
          } 
        } 
      } 
    
      if (is_array($return)) { 
        return $return; 
      } else { 
        return $false; 
      } 
    } 
    ?>
    

提交回复
热议问题