PHP读取XML文件的三种方式

一  用 simplexml_load_file 读取xml文件
 
<?php
    $xml_array=simplexml_load_file('person.xml'); //将XML中的数据,读取到数组对象中

    foreach($xml_array as $tmp)
    {
        echo $tmp->name."-".$tmp->sex."-".$tmp->old."<br>";
    }
?>



二 
DOMDocument读取xml
<?php
    $doc = new DOMDocument(); 
    $doc->load('xml.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"; 
    }  



三  利用正则来获取数据
<?php
header("content-type:text/html;charset=utf-8");

$xml = '';  
$f = fopen("xml.xml", "r"); 

while($data = fread($f, 2096))  
{  
    $xml .= $data;  
}  
fclose($f);  
  
preg_match_all('/\<humans\>(.*?)\<\/humans\>/s', $xml, $humans);  
  
foreach($humans[1] as $human)  
{  
    preg_match_all('/\<name\>(.*?)\<\/name\>/s', $human, $names);  
    preg_match_all('/\<sex\>(.*?)\<\/sex\>/s', $human, $sexes);  
    preg_match_all('/\<old\>(.*?)\<\/old\>/s', $human, $olds);  
}  
  
foreach($names[1] as $k=>$name)  
{  
    echo $names[1][$k].'-'.$sexes[1][$k].'-'.$olds[1][$k]."\n";  
}  


上一篇:Apache 虚拟主机的配置


下一篇:CI框架内置分页代码