溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

php如何解析xml方法

發(fā)布時間:2021-09-03 10:42:54 來源:億速云 閱讀:141 作者:小新 欄目:編程語言

這篇文章主要介紹了php如何解析xml方法,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

books.xml文件如下:

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
 <book category="children">
 <title lang="en">Harry Potter</title>
 <author>J K. Rowling</author>
 <year>2005</year>
 <price>29.99</price>
 </book>
 <book category="cooking">
 <title lang="en">Everyday Italian</title>
 <author>Giada De Laurentiis</author>
 <year>2005</year>
 <price>30.00</price>
 </book>
 <book category="web" cover="paperback">
 <title lang="en">Learning XML</title>
 <author>Erik T. Ray</author>
 <year>2003</year>
 <price>39.95</price>
 </book>
</bookstore>

1、DOM解析XML

<?php
 //創(chuàng)建一個DOMDocument對象
 $doc=new DOMDocument();
 //加載XML文件
 $doc->load("books.xml");
 //獲取所有的book標(biāo)簽
 $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."<br>";
  echo "author:".$author."<br>";
  echo "year:".$year."<br>";
  echo "price:".$price ."<br>";
  echo "***********************************<br>";
 }
?>

2、xml_parse_into_struct

創(chuàng)建解析器,將xml數(shù)據(jù)解析到數(shù)組,釋放解析器,再有就是從數(shù)組中提取想要的值。

<?php
 // 讀取xml文件
 $file = "books.xml";
 $data = file_get_contents($file);
 // 創(chuàng)建解析器
 $parser = xml_parser_create();
 // 將 XML 數(shù)據(jù)解析到數(shù)組中
 xml_parse_into_struct($parser, $data, $vals, $index);
 // 釋放解析器
 xml_parser_free($parser);
 // 數(shù)組處理
 $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 "<pre>";
 print_r($arr);
 echo "</pre>";
?>

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

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

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“php如何解析xml方法”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI