最新消息: 新版网站上线了!!!

php读取xml文件并遍历出来

一、php程序部分

1、方法一 simplexml读取xml

<?php

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

2、方法二 //DOMDocument读取xml

<?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 ".'<br />';
    }
    ?> 
二、xml部分

<?xml version="1.0" encoding="UTF-8" ?>
<OBJECT>

<humans>
<name>hongye</name>
<sex>man</sex>
<old>12age</old>
</humans>

<humans>
<name>han</name>
<sex>man</sex>
<old>14age</old>
</humans>

<humans>
<name>hy</name>
<sex>woman</sex>
<old>17age</old>
</humans>

</OBJECT>

转载请注明:谷谷点程序 » php读取xml文件并遍历出来