作者:黎明前后2502887455 | 来源:互联网 | 2023-05-19 12:29
本文实例讲述了php读取XML的常见方法。分享给大家供大家参考,具体如下:xml源文件<?xmlversion1.0encodingUTF-8?><humans><zhangyin
本文实例讲述了php读取XML的常见方法。分享给大家供大家参考,具体如下:
xml源文件
<&#63;xml version="1.0 encoding="UTF-8"&#63;>
张映
男
28
tank
男
28
1)DOMDocument读取xml
<&#63;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中的值,如
$sexs = $human->getElementsByTagName( "sex" );
$sex = $sexs->item(0)->nodeValue;
$olds = $human->getElementsByTagName( "old" );
$old = $olds->item(0)->nodeValue;
echo "$name - $sex - $old\n";
}
&#63;>
2)simplexml读取xml
<&#63;php
$xml_array=simplexml_load_file('person.xml'); //将XML中的数据,读取到数组对象中
foreach($xml_array as $tmp){
echo $tmp->name."-".$tmp->sex."-".$tmp->old."
";
}
&#63;>
3)用php正则表达式来读取数据
<&#63;php
$xml = "";
$f = fopen('person.xml', 'r');
while( $data = fread( $f, 4096 ) ) {
$xml .= $data;
}
fclose( $f );
// 上面读取数据
preg_match_all( "/\&;humans\&;(.*&#63;)\&;\/humans\&;/s", $xml, $humans ); //匹配最外层标签里面的内容
foreach( $humans[1] as $k=>$human )
{
preg_match_all( "/\&;name\&;(.*&#63;)\&;\/name\&;/", $human, $name ); //匹配出名字
preg_match_all( "/\&;sex\&;(.*&#63;)\&;\/sex\&;/", $human, $sex ); //匹配出性别
preg_match_all( "/\&;old\&;(.*&#63;)\&;\/old\&;/", $human, $old ); //匹配出年龄
}
foreach($name[1] as $key=>$val){
echo $val." - ".$sex[$key][1]." - ".$old[$key][1]."
" ;
}
&#63;>
4)xmlreader来读取xml数据
<&#63;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."
" ;
}
$i++;
}
}
&#63;>
PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:
在线XML/JSON互相转换工具:
http://tools.ddpool.cn/code/xmljson
在线格式化XML/在线压缩XML:
http://tools.ddpool.cn/code/xmlformat
XML在线压缩/格式化工具:
http://tools.ddpool.cn/code/xml_format_compress
XML代码在线格式化美化工具:
http://tools.ddpool.cn/code/xmlcodeformat
希望本文所述对大家PHP程序设计有所帮助。