本文實(shí)例講述了php讀取XML的常見(jiàn)方法。分享給大家供大家參考,具體如下:
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標(biāo)簽的對(duì)象數(shù)組 foreach( $humans as $human ) { $names = $human->getElementsByTagName( "name" ); //取得name的標(biāo)簽的對(duì)象數(shù)組 $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中的數(shù)據(jù),讀取到數(shù)組對(duì)象中 foreach($xml_array as $tmp){ echo $tmp->name."-".$tmp->sex."-".$tmp->old."<br>"; } ?>
3)用php正則表達(dá)式來(lái)讀取數(shù)據(jù)
<?php $xml = ""; $f = fopen('person.xml', 'r'); while( $data = fread( $f, 4096 ) ) { $xml .= $data; } fclose( $f ); // 上面讀取數(shù)據(jù) preg_match_all( "/\<humans\>(.*?)\<\/humans\>/s", $xml, $humans ); //匹配最外層標(biāo)簽里面的內(nèi)容 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來(lái)讀取xml數(shù)據(jù)
<?php $reader = new XMLReader(); $reader->open('person.xml'); //讀取xml數(shù)據(jù) $i=1; while ($reader->read()) { //是否讀取 if ($reader->nodeType == XMLReader::TEXT) { //判斷node類型 if($i%3) { echo $reader->value; //取得node的值 } else { echo $reader->value."<br>" ; } $i++; } } ?>
PS:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress
XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP針對(duì)XML文件操作技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《PHP錯(cuò)誤與異常處理方法總結(jié)》、《PHP基本語(yǔ)法入門教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
【網(wǎng)站聲明】本站除付費(fèi)源碼經(jīng)過(guò)測(cè)試外,其他素材未做測(cè)試,不保證完整性,網(wǎng)站上部分源碼僅限學(xué)習(xí)交流,請(qǐng)勿用于商業(yè)用途。如損害你的權(quán)益請(qǐng)聯(lián)系客服QQ:2655101040 給予處理,謝謝支持。