php读取XML的常见方法实例总结

时间:2022-11-16 13:04:05

本文实例讲述了php读取XML的常见方法。分享给大家供大家参考,具体如下:

xml源文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0 encoding="UTF-8"?>
<humans>
   <zhangying>
     <name>张映</name>
     <sex>男</sex>
     <old>28</old>
   </zhangying>
   <tank>
     <name>tank</name>
     <sex>男</sex>
     <old>28</old>
   </tank>
</humans>

1)DOMDocument读取xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
   $doc = new DOMDocument();
   $doc->load('person.xml'); //读取xml文件
   $humans = $doc->getElementsByTagName( "humans" ); //取得humans标签的对象数组
   foreach( $humans as $human )
   {
     $names = $human->getElementsByTagName( "name" ); //取得name的标签的对象数组
     $name = $names->item(0)->nodeValue; //取得node中的值,如<name> </name>
     $sexs = $human->getElementsByTagName( "sex" );
     $sex = $sexs->item(0)->nodeValue;
     $olds = $human->getElementsByTagName( "old" );
     $old = $olds->item(0)->nodeValue;
     echo "$name - $sex - $old\n";
   }
?>

2)simplexml读取xml

?
1
2
3
4
5
6
<?php
   $xml_array=simplexml_load_file('person.xml'); //将XML中的数据,读取到数组对象中
   foreach($xml_array as $tmp){
     echo $tmp->name."-".$tmp->sex."-".$tmp->old."<br>";
   }
?>

3)用php正则表达式来读取数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
   $xml = "";
   $f = fopen('person.xml', 'r');
   while( $data = fread( $f, 4096 ) ) {
     $xml .= $data;
   }
   fclose( $f );
   // 上面读取数据
   preg_match_all( "/\<humans\>(.*?)\<\/humans\>/s", $xml, $humans ); //匹配最外层标签里面的内容
   foreach( $humans[1] as $k=>$human )
   {
     preg_match_all( "/\<name\>(.*?)\<\/name\>/", $human, $name ); //匹配出名字
     preg_match_all( "/\<sex\>(.*?)\<\/sex\>/", $human, $sex ); //匹配出性别
     preg_match_all( "/\<old\>(.*?)\<\/old\>/", $human, $old ); //匹配出年龄
   }
   foreach($name[1] as $key=>$val){
     echo $val." - ".$sex[$key][1]." - ".$old[$key][1]."<br>" ;
   }
?>

4)xmlreader来读取xml数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
   $reader = new XMLReader();
   $reader->open('person.xml'); //读取xml数据
   $i=1;
   while ($reader->read()) { //是否读取
     if ($reader->nodeType == XMLReader::TEXT) { //判断node类型
       if($i%3) {
         echo $reader->value; //取得node的值
       } else {
         echo $reader->value."<br>" ;
       }
       $i++;
     }
   }
?>

希望本文所述对大家PHP程序设计有所帮助。