欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

将xml转换为数组

程序员文章站 2022-05-05 22:41:33
...
php代码
function xmlNameSpaceToArray(SimpleXmlIterator $xml, $nameSpaces=Null){
      $output = Null;
      $preparedArray = array();
      for($xml->rewind(); $xml->valid(); $xml->next()) {
        	$key = $xml->key();
        	if(!isset($preparedArray[$key])) { $preparedArray[$key] = array(); $i=0; }
        	else $i = count($preparedArray[$key]);
        	$simple = true;
        	foreach($xml->current()->attributes() as $k=>$v) {
            	$preparedArray[$key][$i][$k]=(string)$v;
            	$simple = false;
        	}
        	if($nameSpaces) foreach($nameSpaces as $nid=>$name) {
          	foreach($xml->current()->attributes($name) as $k=>$v) {
             	$preparedArray[$key][$i][$nid.':'.$k]=(string)$v;
             	$simple = false;
          	}
        	} 
        	if($xml->hasChildren()) {
            	if($simple) $preparedArray[$key][$i] = xmlNameSpaceToArray($xml->current(), $nameSpaces);
            	else $preparedArray[$key][$i]['content'] = xmlNameSpaceToArray($xml->current(), $nameSpaces);
        	} else {
            	if($simple) $preparedArray[$key][$i] = strval($xml->current());
            	else $preparedArray[$key][$i]['content'] = strval($xml->current());
        	}
        	$i++;
      }
      $output = $preparedArray;
      return $preparedArray;
}

function xmlToArray($xmlFilePath){
	$xml = new SimpleXmlIterator($xmlFilePath , null, true);
	$nameSpaces = $xml->getNamespaces(true);
	$output = xmlNameSpaceToArray($xml,$nameSpaces);
	return $output;
}

$xmlFilePath = 'http://forums.devshed.com/rss/feed-5.xml';
$output = xmlToArray($xmlFilePath);
print_r($output);
相关标签: 将xml转换为数组