PHP使用DOM和simplexml讀取xml文檔的方法樣本

來源:互聯網
上載者:User
這篇文章主要介紹了PHP使用DOM和simplexml讀取xml文檔的方法,結合執行個體形式分析了php使用DOM及simplxml針對xml檔案的建立、載入、讀取等相關操作技巧,需要的朋友可以參考下

本文執行個體講述了PHP使用DOM和simplexml讀取xml文檔的方法。分享給大家供大家參考,具體如下:

執行個體 用DOM擷取下列xml文檔中所有金庸小說的書名,該xml文檔所在位置為 ./books.xml:

<?xml version="1.0" encoding="utf-8"?><root> <book>  <title>天龍八部</title>  <author>金庸</author> </book> <book>  <title>陸小鳳</title>  <author>古龍</author> </book> <book>  <title>倚天屠龍記</title>  <author>金庸</author> </book> <book>  <title>西遊記</title>  <author>吳承恩</author> </book> <book>  <title>神鵰俠侶</title>  <author>金庸</author> </book> <book>  <title>射鵰英雄傳</title>  <author>金庸</author> </book></root>

用DOM代碼實現:

DOM讀取xml文檔步驟:1、建立DOM對象——》2、載入DOM文檔內容——》3、截取要讀取內容所在的標籤——》獲得要讀取的內容。

header('Content-type:text/html;charset=utf-8');$arr=array();$dom = new DOMDocument();//建立DOM對象$dom->load('./books.xml');//載入xml文檔print_r($dom);echo '<hr>';$dom = $dom->getElementsByTagName('book');//截取標籤for($i=0;$i<$dom->length;$i++){ if($dom->item($i)->childNodes->item(1)->childNodes->item(0)->wholeText=='金庸'){  $arr[] = $dom->item($i)->childNodes->item(0)->childNodes->item(0)->wholeText.'<br />';//擷取內容 }}print_r($arr);

使用 getElementsByTagName 和 childNodes 後返回的都是對象,所以它們後面必須使用 item(int),哪怕它們返回的對象裡面只包含一個項目,也必須用item(0)來指定,否則就會出錯。

用simplexml代碼實現:

$simxml = simplexml_load_file('./books.xml');$t = $simxml->book;$arr=array();foreach ($t as $v){ if($v->author=='金庸'){  $arr[] = (string)$v->title; }}print_r($arr);

使用 simplexml_load_file 後返回的是對象,該對象裡的項目既有對象又有數組,不管是對象還是數組,要迴圈裡面的內容都可以用 foreach。該執行個體最後擷取的內容 $v->title 其實是個對象,所以要用 string 轉化為字串。

聯繫我們

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