這篇文章主要介紹了php讀取XML的常見方法,結合執行個體形式總結了php基於DOMDocument、simplexml、正則及xmlreader讀取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( "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"; }?>
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)用phpRegex來讀取資料
<?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++; } }?>
以上就是本文的全部內容,希望對大家的學習有所協助。