Home >php教程 >PHP源码 >将xml转换为数组

将xml转换为数组

PHP中文网
PHP中文网Original
2016-05-25 17:10:201162browse

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);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php 常用的系统函数Next article: 数字转换中文