本文实例讲述了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 > |
php文件如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<?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>" ; } ?> |
希望本文所述对大家的php程序设计有所帮助。