php讀取XML的常見方法執行個體總結_php技巧

來源:互聯網
上載者:User
這篇文章主要介紹了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++;     }   }?>

以上就是本文的全部內容,希望對大家的學習有所協助。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.