温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php如何解析xml方法

发布时间:2021-09-03 10:42:54 阅读:163 作者:小新 栏目:编程语言
PHP开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

这篇文章主要介绍了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方法”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×