首页 > php教程 > PHP源码 > 正文

将xml转换为数组

PHP中文网
发布: 2016-05-25 17:10:20
原创
1070 人浏览过

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);
登录后复制
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!