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

2025-05-27 0 60

本文实例讲述了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程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 php读取XML的常见方法实例总结 https://www.kuaiidc.com/73023.html

相关文章

发表评论
暂无评论