php解析xml方法執行個體詳解,解析xml執行個體詳解_PHP教程

來源:互聯網
上載者:User

php解析xml方法執行個體詳解,解析xml執行個體詳解


本文以執行個體形式詳細講述了php解析xml方法。分享給大家供大家參考。具體分析如下:

books.xml檔案如下:

<?xml version="1.0" encoding="ISO-8859-1"?>  Harry Potter J K. Rowling 2005 29.99   Everyday Italian Giada De Laurentiis 2005 30.00   Learning XML Erik T. Ray 2003 39.95 

1、DOM解析XML

<?php //建立一個DOMDocument對象 $doc=new DOMDocument(); //載入XML檔案 $doc->load("books.xml"); //擷取所有的book標籤 $bookDom=$doc->getElementsByTagName("book"); foreach($bookDom as $book){  $title = $book->getElementsByTagName("title")->item(0)->nodeValue;  $author = $book->getElementsByTagName("author")->item(0)->nodeValue;  $year = $book->getElementsByTagName("year")->item(0)->nodeValue;  $price = $book->getElementsByTagName("price")->item(0)->nodeValue;  echo "title:".$title."
"; echo "author:".$author."
"; echo "year:".$year."
"; echo "price:".$price ."
"; echo "***********************************
"; }?>

2、xml_parse_into_struct

建立解析器,將xml資料解析到數組,釋放解析器,再有就是從數組中提取想要的值。

<?php // 讀取xml檔案 $file = "books.xml"; $data = file_get_contents($file); // 建立解析器 $parser = xml_parser_create(); // 將 XML 資料解析到數組中 xml_parse_into_struct($parser, $data, $vals, $index); // 釋放解析器 xml_parser_free($parser); // 數組處理 $arr = array(); $t=0; foreach($vals as $value) { $type = $value['type']; $tag = $value['tag']; $level = $value['level']; $attributes = isset($value['attributes'])?$value['attributes']:""; $val = isset($value['value'])?$value['value']:""; switch ($type) {  case 'open':  if ($attributes != "" || $val != "") {   $arr[$t]['tag'] = $tag;   $arr[$t]['attributes'] = $attributes;   $arr[$t]['level'] = $level;   $t++;  }   break;  case "complete":  if ($attributes != "" || $val != "") {   $arr[$t]['tag'] = $tag;   $arr[$t]['attributes'] = $attributes;   $arr[$t]['val'] = $val;   $arr[$t]['level'] = $level;   $t++;  }   break; }  }  echo "
"; print_r($arr); echo "
";?>

3、用 SAX 解析器讀取 XML-----XML Simple API(SAX)解析器

<?php $file="books.xml"; $xml = simplexml_load_file($file); echo "
"; print_r($xml); echo "
";?>

希望本文所述對大家的php程式設計有所協助。

http://www.bkjia.com/PHPjc/998557.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/998557.htmlTechArticlephp解析xml方法執行個體詳解,解析xml執行個體詳解 本文以執行個體形式詳細講述了php解析xml方法。分享給大家供大家參考。具體分析如下: books.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.