php解析xml方法实例详解,解析xml实例详解
本文以实例形式详细讲述了php解析xml方法。分享给大家供大家参考。具体分析如下:
books.xml文件如下:
<?xml version="1.0" encoding="ISO-8859-1"?>Harry Potter J K. Rowling 2005 29.99 Everyday Italian Giada De Laurentiis 2005 30.00 Learning XML Erik T. Ray 2003 39.95
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."
";
echo "author:".$author."
";
echo "year:".$year."
";
echo "price:".$price ."
";
echo "***********************************
";
}
?>
2、xml_parse_into_struct
创建解析器,将xml数据解析到数组,释放解析器,再有就是从数组中提取想要的值。
本书是全面讲述PHP与MySQL的经典之作,书中不但全面介绍了两种技术的核心特性,还讲解了如何高效地结合这两种技术构建健壮的数据驱动的应用程序。本书涵盖了两种技术新版本中出现的最新特性,书中大量实际的示例和深入的分析均来自于作者在这方面多年的专业经验,可用于解决开发者在实际中所面临的各种挑战。 本书内容全面深入,适合各层次PHP和MySQL开发人员阅读,既是优秀的学习教程,也可用作参考手册。
立即学习“PHP免费学习笔记(深入)”;
<?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 "";
print_r($arr);
echo "
";
?>
3、用 SAX 解析器读取 XML-----XML Simple API(SAX)解析器
<?php
$file="books.xml";
$xml = simplexml_load_file($file);
echo "";
print_r($xml);
echo "
";
?>
希望本文所述对大家的php程序设计有所帮助。










