>백엔드 개발 >PHP 튜토리얼 >php解析xml方法实例详解,解析xml实例详解_PHP教程

php解析xml方法实例详解,解析xml实例详解_PHP教程

WBOY
WBOY원래의
2016-07-13 09:54:08913검색

php解析xml方法实例详解,解析xml实例详解

本文以实例形式详细讲述了php解析xml方法。分享给大家供大家参考。具体分析如下:

books.xml文件如下:

<&#63;xml version="1.0" encoding="ISO-8859-1"&#63;>
<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

<&#63;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."<br>";
  echo "author:".$author."<br>";
  echo "year:".$year."<br>";
  echo "price:".$price ."<br>";
  echo "***********************************<br>";
 }
&#63;>

2、xml_parse_into_struct

创建解析器,将xml数据解析到数组,释放解析器,再有就是从数组中提取想要的值。

<&#63;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'])&#63;$value['attributes']:"";
 $val = isset($value['value'])&#63;$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 class="brush:php;toolbar:false">";
 print_r($arr);
 echo "
"; ?>

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

<&#63;php
 $file="books.xml";
 $xml = simplexml_load_file($file);
 echo "<pre class="brush:php;toolbar:false">";
 print_r($xml);
 echo "
"; ?>

希望本文所述对大家的php程序设计有所帮助。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/998557.htmlTechArticlephp解析xml方法实例详解,解析xml实例详解 本文以实例形式详细讲述了php解析xml方法。分享给大家供大家参考。具体分析如下: books.xml文件...
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.