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

将xml转换为数组

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

php代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

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);

登录后复制
相关标签:
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板