解析XML数据,必看
xml源文件
- <?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
- <?php
- $doc = new DOMDocument();
- $doc->load('person.xml'); //读取xml文件
- $humans = $doc->getElementsByTagName_r( "humans" ); //取得humans标签的对象数组
- foreach( $humans as $human )
- {
- $names = $human->getElementsByTagName_r( "name" ); //取得name的标签的对象数组
- $name = $names->item(0)->nodeValue; //取得node中的值,如<name> </name>
- $sexs = $human->getElementsByTagName_r( "sex" );
- $sex = $sexs->item(0)->nodeValue;
- $olds = $human->getElementsByTagName_r( "old" );
- $old = $olds->item(0)->nodeValue;
- echo "$name - $sex - $oldn";
- }
- ?>
<?php
//创建一个DOMDocument对象
$doc
=
new
DOMDocument();
//加载XML文件
$doc
->load(
"books.xml"
);
//获取所有的book标签
$bookDom
=
$doc
->getElementsByTagName(
"book"
);
foreach
(
$bookDom
as
$book
){
$title
=
$book
->getElementsByTagName(
"title"
)->item(0)->nodeValue;
$author
=
$book
->getElementsByTagName(
"author"
)->item(0)->nodeValue;
$year
=
$book
->getElementsByTagName(
"year"
)->item(0)->nodeValue;
$price
=
$book
->getElementsByTagName(
"price"
)->item(0)->nodeValue;
echo
"title:"
.
$title
.
"<br>"
;
echo
"author:"
.
$author
.
"<br>"
;
echo
"year:"
.
$year
.
"<br>"
;
echo
"price:"
.
$price
.
"<br>"
;
echo
"***********************************<br>"
;
}
?>
单条就不必循环了:
$dom->load($url1);
$status = $dom->getElementsByTagName( "productStatusName" ); //取得productStatusName的标签的对象数组
$status = $status->item(0)->nodeValue;
复制代码
2)simplexml读取xml
- <?php
- $xml_array=simplexml_load_file('person.xml'); //将XML中的数据,读取到数组对象中
- foreach($xml_array as $tmp){
- echo $tmp->name."-".$tmp->sex."-".$tmp->old."<br>";
- }
- ?>
复制代码
3)用php正则表达式来记取数据
- <?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数据
- <?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++;
- }
- }
- ?>
A buddhist programmer.