Home > php教程 > php手册 > PHP通过DOM解析XML文件或者xml字符串

PHP通过DOM解析XML文件或者xml字符串

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-13 10:43:31
Original
1204 people have browsed it

 

 

上一篇记录了php创建xml文档的过程,这篇将记录如何把接受到的xml字符串中的数据和属性值解析出来,以便进一步对数据进行处理。

xml文件

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.  

42.  

43.  

44.  

45.  

46.  

47.  

1.            $xml = new DOMDocument();

2.            

3.            //$xml->load("timeline.xml");

4.            $xmlstring = '';

5.            $xml->loadXML($xmlstring);

6.            

7.            $timedom = $xml->getElementsByTagName("time");

8.            $d_array = array();

9.            foreach ($timedom as $times){

10.               $time_att_value = $times->getAttribute("value");

11.               echo $time_att_value."
";

12.               $d_worker = $times->getElementsByTagName("worker");

13.               foreach ($d_worker as $d_work){

14.                   $worker_att_id = $d_work->getAttribute("id");

15.                   $worker_att_name = $d_work->getAttribute("name");

16.                   echo $worker_att_name."
";

17.                   //echo $worker_att_id."
";

18.                   $d_hours = $d_work->getElementsByTagName("hour");

19.                   foreach ($d_hours as $d_hour){

20.                       $hour_att_pid = $d_hour->getAttribute("pid");

21.                       $hour_att_pmid = $d_hour->getAttribute("pmid");

22.                      

23.                       echo count($d_hour);

24.                       echo $d_hour->nodeValue."
";

25.                   }

26.               }

27.           }

如果是xml文件,则用

$xml->load("timeline.xml");

如果是解析xml字符串则用

$xml->loadXML($xmlstring);

------------------------------------------------------

获得节点属性:getAttribute('id');

获得节点值:nodeValue;

本文出自 “Bob” 博客

Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template