一 用
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";
}
|
标签:XML,xml,old,读取,humans,names,human,PHP,name
来源: https://blog.51cto.com/libinblog/2977167