使用PHP 5.0 轻松解析XML文档(1)
xml
用sax方式的时候,要自己构建3个函数,而且要直接用这三的函数来返回数据, 要求较强的逻辑。 在处理不同结构的xml的时候, 还要重新进行构造这三个函数,麻烦!
用dom方式,倒是好些,但是他把每个节点都看作是一个node,操作起来要写好多的代码, 麻烦!
网上有好多的开源的xml解析的类库, 以前看过几个,但是心里总是觉得不踏实,感觉总是跟在别人的屁股后面.
这几天在搞java, 挺累的,所以决定换换脑袋,写点php代码,为了防止以后xml解析过程再令我犯难,就花了一天的时间写了下面一个xml解析的类,于是就有了下面的东西。
实现方式是通过包装"sax方式的解析结果"来实现的. 总的来说,对于我个人来说挺实用的,性能也还可以,基本上可以完成大多数的处理要求。
功能:
1、 对基本的xml文件的节点进行 查询 / 添加 / 修改 / 删除 工作.
2、导出xml文件的所有数据到一个数组里面.
3、整个设计采用了oo方式,在操作结果集的时候, 使用方法类似于dom
缺点:
1、 每个节点最好都带有一个id(看后面的例子), 每个“节点名字”=“节点的标签_节点的id”,如果这个id值没有设置,程序将自动给他产生一个id,这个id就是这个节点在他的上级节点中的位置编号,从0开始。
2、 查询某个节点的时候可以通过用“|”符号连接“节点名字”来进行。这些“节点名字”都是按顺序写好的上级节点的名字。
使用说明:
运行下面的例子,在执行结果页面上可以看到函数的使用说明
代码是通过php5来实现的,在php4中无法正常运行。
由于刚刚写完,所以没有整理文档,下面的例子演示的只是一部分的功能,代码不是很难,要是想知道更多的功能,可以研究研究源代码。
目录结构:
test.php test.xml xml / SimpleDocumentBase.php xml / SimpleDocumentNode.php xml / SimpleDocumentRoot.php xml / SimpleDocumentParser.php
<?xml version="1.0" encoding="GB2312"?><br><shop><br> <name>华联</name><br> <address>北京长安街-9999号</address><br> <desc>连锁超市</desc><br> <cat id="food"><br> <goods id="food11"><br> <name>food11</name><br> <price>12.90</price><br> </goods><br> <goods id="food12"><br> <name>food12</name><br> <price>22.10</price><br> <desc creator="hahawen">好东西推荐</desc><br> </goods><br> </cat><br> <cat><br> <goods id="tel21"><br> <name>tel21</name><br> <price>1290</price><br> </goods><br> </cat><br> <cat id="coat"><br> <goods id="coat31"><br> <name>coat31</name><br> <price>112</price><br> </goods><br> <goods id="coat32"><br> <name>coat32</name><br> <price>45</price><br> </goods><br> </cat><br> <special id="hot"><br> <goods><br> <name>hot41</name><br> <price>99</price><br> </goods><br> </special><br></shop>
文件:test.php
<?php require_once "xml/SimpleDocumentParser.php";<br> require_once "xml/SimpleDocumentBase.php";<br> require_once "xml/SimpleDocumentRoot.php";<br> require_once "xml/SimpleDocumentNode.php";<br> $test = new SimpleDocumentParser();<br> $test->parse("test.xml");<br> $dom = $test->getSimpleDocument();<br> echo "<pre>";<br> echo "<hr><font color=red>";<br> echo "下面是通过函数getSaveData()返回的整个xml数据的数组";<br> echo "</font><hr>";<br> print_r($dom->getSaveData());<br> echo "<hr><font color=red>";<br> echo "下面是通过setValue()函数,给给根节点添加信息,添加后显示出结果xml文件的内容";<br> echo "</font><hr>";<br> $dom->setValue("telphone", "123456789");<br> echo htmlspecialchars($dom->getSaveXml());<br> echo "<hr><font color=red>";<br> echo "下面是通过getNode()函数,返回某一个分类下的所有商品的信息";<br> echo "</font><hr>";<br> $obj = $dom->getNode("cat_food");<br> $nodeList = $obj->getNode();<br> foreach($nodeList as $node){<br> $data = $node->getValue();<br> echo "<font color=red>商品名:".$data[name]."</font><br>";<br> print_R($data);<br> print_R($node->getAttribute());<br> }<br> echo "<hr><font color=red>";<br> echo "下面是通过findNodeByPath()函数,返回某一商品的信息";<br> echo "</font><hr>";<br> $obj = $dom->findNodeByPath("cat_food|goods_food11");<br> if(!is_object($obj)){<br> echo "该商品不存在";<br> }else{<br> $data = $obj->getValue();<br> echo "<font color=red>商品名:".$data[name]."</font><br>";<br> print_R($data);<br> print_R($obj->getAttribute());<br> }<br> echo "<hr><font color=red>";<br> echo "下面是通过setValue()函数,给商品\"food11\"添加属性, 然后显示添加后的结果";<br> echo "</font><hr>";<br> $obj = $dom->findNodeByPath("cat_food|goods_food11");<br> $obj->setValue("leaveword", array("value"=>"这个商品不错",<br> "attrs"=>array("author"=>"hahawen", "date"=>date('Y-m-d'))));<br> echo htmlspecialchars($dom->getSaveXml());<br> echo "<hr><font color=red>";<br> echo "下面是通过removeValue()/removeAttribute()函数,<br> 给商品\"food11\"改变和删除属性, 然后显示操作后的结果";<br> echo "</font><hr>";<br> $obj = $dom->findNodeByPath("cat_food|goods_food12");<br> $obj->setValue("name", "new food12");<br> $obj->removeValue("desc");<br> echo htmlspecialchars($dom->getSaveXml());<br> echo "<hr><font color=red>";<br> echo "下面是通过createNode()函数,添加商品, 然后显示添加后的结果";<br> echo "</font><hr>";<br> $obj = $dom->findNodeByPath("cat_food");<br> $newObj = $obj->createNode("goods", array("id"=>"food13"));<br> $newObj->setValue("name", "food13");<br> $newObj->setValue("price", 100);<br> echo htmlspecialchars($dom->getSaveXml());<br> echo "<hr><font color=red>";<br> echo "下面是通过removeNode()函数,删除商品, 然后显示删除后的结果";<br> echo "</font><hr>";<br> $obj = $dom->findNodeByPath("cat_food");<br> $obj->removeNode("goods_food12");<br> echo htmlspecialchars($dom->getSaveXml());<br> ?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

Use PHPXML functions to process XML data: Parse XML data: simplexml_load_file() and simplexml_load_string() load XML files or strings. Access XML data: Use the properties and methods of the SimpleXML object to obtain element names, attribute values, and subelements. Modify XML data: add new elements and attributes using the addChild() and addAttribute() methods. Serialized XML data: The asXML() method converts a SimpleXML object into an XML string. Practical example: parse product feed XML, extract product information, transform and store it into a database.

Using Python to implement data validation in XML Introduction: In real life, we often deal with a variety of data, among which XML (Extensible Markup Language) is a commonly used data format. XML has good readability and scalability, and is widely used in various fields, such as data exchange, configuration files, etc. When processing XML data, we often need to verify the data to ensure the integrity and correctness of the data. This article will introduce how to use Python to implement data verification in XML and give the corresponding

In today's era of rapid technological development, programming languages are springing up like mushrooms after a rain. One of the languages that has attracted much attention is the Go language, which is loved by many developers for its simplicity, efficiency, concurrency safety and other features. The Go language is known for its strong ecosystem with many excellent open source projects. This article will introduce five selected Go language open source projects and lead readers to explore the world of Go language open source projects. KubernetesKubernetes is an open source container orchestration engine for automated
