php操作xml的方法

來源:互聯網
上載者:User

標籤:style   blog   io   color   os   ar   for   sp   strong   

 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++; } } ?> 

 

  三,小結

  讀取xml的方法很多,簡單舉幾個。上面四種方法都是可以把標籤中的資料讀出來,張映.但是他們的測重點不同,前三種方 法的讀取xml的function的設計重點,是為了讀取標籤中的值,相當於jquery中的text()方法,而xmlreader呢他就不太一樣,他 的重點不在讀取標籤中的值,而讀取標籤的屬性,把要傳送的資料,都放在屬性中(不過我上面寫的那個方法還是取標籤中的值,因為xml檔案已經給定了,我就 不想在搞xml檔案出來了)。

  舉個例子解釋一下,

  <data name=’張映’ sex=’男’ old=’28′></data>

  xmlreader的設計重點是為了讀data裡面的name sex old的值,而讀取的內容就比較麻煩了。他相當於jquery中attr(”);這個東西。

  上面純屬個人看法,請大家指正。希望對大家有協助。

php操作xml的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.