旗下导航:搜·么
当前位置:网站首页 > XML教程 > 正文

php剖析xml要领实例(附代码)细致申明【XML教程】,php,解析xml

作者:搜教程发布时间:2019-12-01分类:XML教程浏览:85评论:0


导读:这篇文章重要引见了php剖析xml要领,以实例情势细致分析了php剖析XML的相干技能,须要的朋侪能够参考下本文以实例情势细致报告了php剖析xml要领。分享给人人供人人参...
这篇文章重要引见了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>";
?>

以上就是php剖析xml要领实例(附代码)细致申明的细致内容,更多请关注ki4网别的相干文章!

标签:php解析xml


欢迎 发表评论: