这篇文章主要介绍了php解析xml方法,以实例形式详细分析了php解析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>";?>

更多相关文章

  1. Parse XML Tree 解析XML文件的代码实例
  2. XML解析器-在js中解析xml文件
  3. XML文件解析汇总SAX/DOM/PULL的详细介绍
  4. 了解xml的几种文件格式
  5. 使用PULL解析XML文件时循环过程的示例代码分享
  6. 详细介绍Android 解析XML文件和生成XML文件的示例代码
  7. XML文件数减少的示例代码分享
  8. 具体介绍使用XmlReader读取xml文件的代码案例
  9. xml,文件操作功能类的示例代码详解

随机推荐

  1. PHP按照 年、月、日创建递归目录
  2. PHP的语言特性-面向对象和C++/java/pytho
  3. 刷新php页面而不重载内容?
  4. 在php中,从字符串中删除逗号后的所有内容
  5. php,检查文本拆分的正确性
  6. 在php中调用父方法的多种方法
  7. centos7 升级php版本
  8. php 正则问题 \s的疑问,求教。。。。
  9. 我如何使用Wikipedia API
  10. 使用Laravel在PHP中按时间戳,后端过滤SQL