欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php解析xml方法实例详解

程序员文章站 2022-06-29 17:31:34
本文以实例形式详细讲述了php解析xml方法。分享给大家供大家参考。具体分析如下: books.xml文件如下:

本文以实例形式详细讲述了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
 //创建一个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>";
 }
?>

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 "<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>";
?>

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