0

0

用php5轻松解析xml

php中文网

php中文网

发布时间:2016-06-21 09:06:54

|

1288人浏览过

|

来源于php中文网

原创

php5|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\ 查询某个节点的时候可以通过用“|”符号连接“节点名字”来进行。这些“节点名字”都是按顺序写好的上级节点的名字。

使用说明:
运行下面的例子,在执行结果页面上可以看到函数的使用说明

网亚Net!B2B
网亚Net!B2B

网亚Net!B2B从企业信息化服务的整体解决方案上提供了实用性的电子商务建站部署,企业无需进行复杂的网站开发,直接使用Net!B2B系列,就能轻松构建具有竞争力的行业门户网站,如果您有特殊需要,系统内置的模板体系和接口体系,让网站可以按照自己的个性要求衍生出庞大的门户服务需求,网亚Net!B2B电子商务建站系统可以让您以希望的方式开展网上服务,无论是为您的客户提供信息服务,新闻服务,产品展示与产品

下载

代码是通过php5来实现的,在php4中无法正常运行。

由于刚刚写完,所以没有整理文档,下面的例子演示的只是一部分的功能,代码不是很难,要是想知道更多的功能,可以研究研究源代码。

目录结构:

      test.php      test.xml      xml / SimpleDocumentBase.php      xml / SimpleDocumentNode.php      xml / SimpleDocumentRoot.php      xml / SimpleDocumentParser.php
文件:test.xml


华联
北京长安街-9999号

连锁超市


food11
12.90


food12
22.10
好东西推荐




tel21
1290




coat31
112


coat32
45




hot41
99


文件:test.php

require_once "xml/SimpleDocumentParser.php";
require_once "xml/SimpleDocumentBase.php";
require_once "xml/SimpleDocumentRoot.php";
require_once "xml/SimpleDocumentNode.php";

$test = new SimpleDocumentParser();
$test->parse("test.xml");
$dom = $test->getSimpleDocument();

echo "

";

echo "


";
echo "下面是通过函数getSaveData()返回的整个xml数据的数组";
echo "

";
print_r($dom->getSaveData());

echo "


";
echo "下面是通过setValue()函数,给给根节点添加信息,添加后显示出结果xml文件的内容";
echo "

";
$dom->setValue("telphone", "123456789");
echo htmlspecialchars($dom->getSaveXml());

echo "


";
echo "下面是通过getNode()函数,返回某一个分类下的所有商品的信息";
echo "

";
$obj = $dom->getNode("cat_food");
$nodeList = $obj->getNode();
foreach($nodeList as $node){
$data = $node->getValue();
echo "商品名:".$data[name]."
";
print_R($data);
print_R($node->getAttribute());
}

echo "


";
echo "下面是通过findNodeByPath()函数,返回某一商品的信息";
echo "

";
$obj = $dom->findNodeByPath("cat_food|goods_food11");
if(!is_object($obj)){
echo "该商品不存在";
}else{
$data = $obj->getValue();
echo "商品名:".$data[name]."
";
print_R($data);
print_R($obj->getAttribute());
}

echo "


";
echo "下面是通过setValue()函数,给商品\"food11\"添加属性, 然后显示添加后的结果";
echo "

";
$obj = $dom->findNodeByPath("cat_food|goods_food11");
$obj->setValue("leaveword", array("value"=>"这个商品不错", "attrs"=>array("author"=>"hahawen", "date"=>date('Y-m-d'))));
echo htmlspecialchars($dom->getSaveXml());

echo "


";
echo "下面是通过removeValue()/removeAttribute()函数,给商品\"food11\"改变和删除属性, 然后显示操作后的结果";
echo "

";
$obj = $dom->findNodeByPath("cat_food|goods_food12");
$obj->setValue("name", "new food12");
$obj->removeValue("desc");
echo htmlspecialchars($dom->getSaveXml());

echo "


";
echo "下面是通过createNode()函数,添加商品, 然后显示添加后的结果";
echo "

";
$obj = $dom->findNodeByPath("cat_food");
$newObj = $obj->createNode("goods", array("id"=>"food13"));
$newObj->setValue("name", "food13");
$newObj->setValue("price", 100);
echo htmlspecialchars($dom->getSaveXml());

echo "


";
echo "下面是通过removeNode()函数,删除商品, 然后显示删除后的结果";
echo "

";
$obj = $dom->findNodeByPath("cat_food");
$obj->removeNode("goods_food12");
echo htmlspecialchars($dom->getSaveXml());

?>

文件:SimpleDocumentParser.php
 * @since      2004-12-04 * @copyright  Copyright (c) 2004, NxCoder Group * *========================================================= *//** * class SimpleDocumentParser * use SAX parse xml file, and build SimpleDocumentObject * all this pachage's is work for xml file, and method is action as DOM. * * @package SmartWeb.common.xml * @version 1.0 */class SimpleDocumentParser{ private $domRootObject = null; private $currentNO = null; private $currentName = null; private $currentValue = null; private $currentAttribute = null; public function getSimpleDocument() {     return $this->domRootObject; } public function parse($file) {        $xmlParser = xml_parser_create();     xml_parser_set_option($xmlParser,XML_OPTION_CASE_FOLDING, 0);     xml_parser_set_option($xmlParser,XML_OPTION_SKIP_WHITE, 1);     xml_parser_set_option($xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');     xml_set_object($xmlParser, $this);     xml_set_element_handler($xmlParser, "startElement", "endElement");     xml_set_character_data_handler($xmlParser, "characterData");        if (!xml_parse($xmlParser, file_get_contents($file)))            die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xmlParser)), xml_get_current_line_number($xmlParser)));     xml_parser_free($xmlParser); } private function startElement($parser, $name, $attrs) {        $this->currentName = $name;        $this->currentAttribute = $attrs;        if($this->currentNO == null)        {         $this->domRootObject = new SimpleDocumentRoot($name);         $this->currentNO = $this->domRootObject;        }        else        {         $this->currentNO = $this->currentNO->createNode($name, $attrs);        } }    private function endElement($parser, $name)    {        if($this->currentName==$name)        {         $seq = $this->currentNO->getSeq();
$this->currentNO = $this->currentNO->getPNodeObject();
$tag = $this->currentNO->getNodeName($seq);
         if($this->currentAttribute!=null && sizeof($this->currentAttribute)>0)          $this->currentNO->setValue($name, array('value'=>$this->currentValue, 'attrs'=>$this->currentAttribute));         else                $this->currentNO->setValue($name, $this->currentValue);            $this->currentNO->removeNode($tag);        }        else        {      $this->currentNO = (is_a($this->currentNO, 'SimpleDocumentRoot'))? null: $this->currentNO->getPNodeObject();        } } private function characterData($parser, $data) {        $this->currentValue = iconv('UTF-8', 'GB2312', $data); } function __destruct() {     unset($this->domRootObject); }}?>
文件:SimpleDocumentBase.php
 * @since      2004-12-04 * @copyright  Copyright (c) 2004, NxCoder Group * *========================================================= *//** * abstract class SimpleDocumentBase * base class for xml file parse * all this pachage's is work for xml file, and method is action as DOM. * * 1\ add/update/remove data of xml file. * 2\ explode data to array. * 3\ rebuild xml file * * @package SmartWeb.common.xml * @abstract * @version 1.0 */abstract class SimpleDocumentBase{ private $nodeTag = null; private $attributes = array(); private $values = array(); private $nodes = array();    function __construct($nodeTag)    {        $this->nodeTag = $nodeTag;    }    public function getNodeTag()    {     return $this->nodeTag;    }    public function setValues($values){     $this->values = $values;    }    public function setValue($name, $value)    {     $this->values[$name] = $value;    }    public function getValue($name=null)    {     return $name==null? $this->values: $this->values[$name];    }    public function removeValue($name)    {     unset($this->values["$name"]);    }    public function setAttributes($attributes){        $this->attributes = $attributes;    }    public function setAttribute($name, $value)    {     $this->attributes[$name] = $value;    }    public function getAttribute($name=null)    {        return $name==null? $this->attributes: $this->attributes[$name];    }    public function removeAttribute($name)    {     unset($this->attributes["$name"]);    }    public function getNodesSize()    {        return sizeof($this->nodes);    }    protected function setNode($name, $nodeId)    {     $this->nodes[$name] = $nodeId;    }    public abstract function createNode($name, $attributes);    public abstract function removeNode($name);    public abstract function getNode($name=null);    protected function getNodeId($name=null)    {     return $name==null? $this->nodes: $this->nodes[$name];    }
    public function getNodeName($id)
{
$tmp = array_flip($this->nodes);
return $tmp[$id];
} protected function createNodeByName($rootNodeObj, $name, $attributes, $pId) { $tmpObject = $rootNodeObj->createNodeObject($pId, $name, $attributes); $key = isset($attributes[id])? $name.'_'.$attributes[id]: $name.'_'.$this->getNodesSize(); $this->setNode($key, $tmpObject->getSeq()); return $tmpObject; } protected function removeNodeByName($rootNodeObj, $name) { $rootNodeObj->removeNodeById($this->getNodeId($name)); if(sizeof($this->nodes)==1) $this->nodes = array(); else unset($this->nodes[$name]); } protected function getNodeByName($rootNodeObj, $name=null) { if($name==null) { $tmpList = array(); $tmpIds = $this->getNodeId(); foreach($tmpIds as $key=>$id) $tmpList[$key] = $rootNodeObj->getNodeById($id); return $tmpList; } else { $id = $this->getNodeId($name); if($id===null) { $tmpIds = $this->getNodeId(); foreach($tmpIds as $tkey=>$tid) { if(strpos($key, $name)==0) { $id = $tid; break; } } } return $rootNodeObj->getNodeById($id); } } public function findNodeByPath($path) { $pos = strpos($path, '|'); if($pos<=0) { return $this->getNode($path); } else { $tmpObj = $this->getNode(substr($path, 0, $pos)); return is_object($tmpObj)? $tmpObj->findNodeByPath(substr($path, $pos+1)): null; } } public function getSaveData() { $data = $this->values; if(sizeof($this->attributes)>0) $data[attrs] = $this->attributes; $nodeList = $this->getNode(); if($nodeList==null) return $data; foreach($nodeList as $key=>$node) { $data[$key] = $node->getSaveData(); } return $data; } public function getSaveXml($level=0) { $prefixSpace = str_pad("", $level, "\t"); $str = "$prefixSpace<$this->nodeTag"; foreach($this->attributes as $key=>$value) $str .= " $key=\"$value\""; $str .= ">\r\n"; foreach($this->values as $key=>$value){ if(is_array($value)) { $str .= "$prefixSpace\t<$key"; foreach($value[attrs] as $attkey=>$attvalue) $str .= " $attkey=\"$attvalue\""; $tmpStr = $value[value]; } else { $str .= "$prefixSpace\t<$key"; $tmpStr = $value; } $tmpStr = trim(trim($tmpStr, "\r\n")); $str .= ($tmpStr===null || $tmpStr==="")? " />\r\n": ">$tmpStr\r\n"; } foreach($this->getNode() as $node) $str .= $node->getSaveXml($level+1)."\r\n"; $str .= "$prefixSpacenodeTag>"; return $str; } function __destruct() { unset($this->nodes, $this->attributes, $this->values); }}?>
文件:SimpleDocumentRoot.php
 * @since      2004-12-04 * @copyright  Copyright (c) 2004, NxCoder Group * *========================================================= *//** * class SimpleDocumentRoot * xml root class, include values/attributes/subnodes. * all this pachage's is work for xml file, and method is action as DOM. * * @package SmartWeb.common.xml * @version 1.0 */class SimpleDocumentRoot extends SimpleDocumentBase{ private $prefixStr = ''; private $nodeLists = array(); function __construct($nodeTag) {        parent::__construct($nodeTag); }    public function createNodeObject($pNodeId, $name, $attributes)    {     $seq = sizeof($this->nodeLists);     $tmpObject = new SimpleDocumentNode($this, $pNodeId, $name, $seq);     $tmpObject->setAttributes($attributes);     $this->nodeLists[$seq] = $tmpObject;     return $tmpObject;    }    public function removeNodeById($id)    {        if(sizeof($this->nodeLists)==1)            $this->nodeLists = array();     else      unset($this->nodeLists[$id]);    }    public function getNodeById($id)    {     return $this->nodeLists[$id];    }    public function createNode($name, $attributes)    {        return $this->createNodeByName($this, $name, $attributes, -1);    }    public function removeNode($name)    {        return $this->removeNodeByName($this, $name);    }    public function getNode($name=null)    {        return $this->getNodeByName($this, $name);    }    public function getSaveXml()    {     $prefixSpace = "";     $str = $this->prefixStr."\r\n";     return $str.parent::getSaveXml(0);    }}?>
文件:SimpleDocumentNode.php
 * @since      2004-12-04 * @copyright  Copyright (c) 2004, NxCoder Group * *========================================================= *//** * class SimpleDocumentNode * xml Node class, include values/attributes/subnodes. * all this pachage's is work for xml file, and method is action as DOM. * * @package SmartWeb.common.xml * @version 1.0 */class SimpleDocumentNode extends SimpleDocumentBase{ private $seq = null; private $rootObject = null;    private $pNodeId = null;    function __construct($rootObject, $pNodeId, $nodeTag, $seq)    {     parent::__construct($nodeTag);        $this->rootObject = $rootObject;        $this->pNodeId = $pNodeId;        $this->seq = $seq;    }    public function getPNodeObject()    {     return ($this->pNodeId==-1)? $this->rootObject: $this->rootObject->getNodeById($this->pNodeId);    }    public function getSeq(){     return $this->seq;    }    public function createNode($name, $attributes)    {        return $this->createNodeByName($this->rootObject, $name, $attributes, $this->getSeq());    }    public function removeNode($name)    {        return $this->removeNodeByName($this->rootObject, $name);    }    public function getNode($name=null)    {        return $this->getNodeByName($this->rootObject, $name);    }}?>
下面是例子运行对结果:

下面是通过函数getSaveData()返回的整个xml数据的数组
Array( [name] => 华联 [address] => 北京长安街-9999号 [desc] => 连锁超市 [cat_food] => Array ( [attrs] => Array ( [id] => food ) [goods_food11] => Array ( [name] => food11 [price] => 12.90 [attrs] => Array ( [id] => food11 ) ) [goods_food12] => Array ( [name] => food12 [price] => 22.10 [desc] => Array ( [value] => 好东西推荐 [attrs] => Array ( [creator] => hahawen ) ) [attrs] => Array ( [id] => food12 ) ) ) [cat_1] => Array ( [goods_tel21] => Array ( [name] => tel21 [price] => 1290 [attrs] => Array ( [id] => tel21 ) ) ) [cat_coat] => Array ( [attrs] => Array ( [id] => coat ) [goods_coat31] => Array ( [name] => coat31 [price] => 112 [attrs] => Array ( [id] => coat31 ) ) [goods_coat32] => Array ( [name] => coat32 [price] => 45 [attrs] => Array ( [id] => coat32 ) ) ) [special_hot] => Array ( [attrs] => Array ( [id] => hot ) [goods_0] => Array ( [name] => hot41 [price] => 99 ) ))
下面是通过setValue()函数,给给根节点添加信息,添加后显示出结果xml文件的内容
华联
北京长安街-9999号
连锁超市 123456789 food11 12.90 food12 22.10 好东西推荐 tel21 1290 coat31 112 coat32 45 hot41 99

下面是通过getNode()函数,返回某一个分类下的所有商品的信息
商品名:food11
Array( [name] => food11 [price] => 12.90)Array( [id] => food11)商品名:food12
Array( [name] => food12 [price] => 22.10 [desc] => Array ( [value] => 好东西推荐 [attrs] => Array ( [creator] => hahawen ) ))Array( [id] => food12)
下面是通过findNodeByPath()函数,返回某一商品的信息
商品名:food11
Array( [name] => food11 [price] => 12.90)Array( [id] => food11)
下面是通过setValue()函数,给商品"food11"添加属性, 然后显示添加后的结果
华联
北京长安街-9999号
连锁超市 123456789 food11 12.90 这个商品不错 food12 22.10 好东西推荐 tel21 1290 coat31 112 coat32 45 hot41 99

下面是通过removeValue()/removeAttribute()函数,给商品"food11"改变和删除属性, 然后显示操作后的结果
华联
北京长安街-9999号
连锁超市 123456789 food11 12.90 这个商品不错 new food12 22.10 tel21 1290 coat31 112 coat32 45 hot41 99

下面是通过createNode()函数,添加商品, 然后显示添加后的结果
华联
北京长安街-9999号
连锁超市 123456789 food11 12.90 这个商品不错 new food12 22.10 food13 100 tel21 1290 coat31 112 coat32 45 hot41 99

下面是通过removeNode()函数,删除商品, 然后显示删除后的结果
华联
北京长安街-9999号
连锁超市 123456789 food11 12.90 这个商品不错 food13 100 tel21 1290 coat31 112 coat32 45 hot41 99



PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
抖音网页版入口与视频观看指南 抖音官网视频在线访问
抖音网页版入口与视频观看指南 抖音官网视频在线访问

本专题汇总了抖音网页版的入口链接、官方登录页面以及视频观看入口,帮助用户快速访问抖音网页版,提供免登录访问方式和直接进入视频播放页面的方法,确保顺利浏览和观看抖音视频。

31

2026.02.04

学习通网页版入口与在线学习指南 学习通官网登录与使用方法
学习通网页版入口与在线学习指南 学习通官网登录与使用方法

本专题详细汇总了学习通网页版入口与登录方法,提供学习通官方网页端入口、学生登录平台、网页版使用指南等内容,帮助用户快速稳定地登录学习通官网,顺利进入学习平台,提升学习效率和体验。

6

2026.02.04

Python Web 框架 Django 深度开发
Python Web 框架 Django 深度开发

本专题系统讲解 Python Django 框架的核心功能与进阶开发技巧,包括 Django 项目结构、数据库模型与迁移、视图与模板渲染、表单与认证管理、RESTful API 开发、Django 中间件与缓存优化、部署与性能调优。通过实战案例,帮助学习者掌握 使用 Django 快速构建功能全面的 Web 应用与全栈开发能力。

7

2026.02.04

Java 流式处理与 Apache Kafka 实战
Java 流式处理与 Apache Kafka 实战

本专题专注讲解 Java 在流式数据处理与消息队列系统中的应用,系统讲解 Apache Kafka 的基础概念、生产者与消费者模型、Kafka Streams 与 KSQL 流式处理框架、实时数据分析与监控,结合实际业务场景,帮助开发者构建 高吞吐量、低延迟的实时数据流管道,实现高效的数据流转与处理。

3

2026.02.04

Golang 容器化与 Docker 实战
Golang 容器化与 Docker 实战

本专题深入讲解 Golang 应用的容器化与 Docker 部署,涵盖 Docker 基础概念、容器构建与镜像管理、Go 应用的 Dockerfile 编写、跨平台容器部署与优化、Docker Compose 和 Kubernetes 部署工具。通过实际案例,帮助学习者掌握 如何将 Golang 应用容器化并实现高效部署与管理,提升系统的可扩展性与运维效率。

3

2026.02.04

全国统一发票查询平台入口合集
全国统一发票查询平台入口合集

本专题整合了全国统一发票查询入口地址合集,阅读专题下面的文章了解更多详细入口。

59

2026.02.03

短剧入口地址汇总
短剧入口地址汇总

本专题整合了短剧app推荐平台,阅读专题下面的文章了解更多详细入口。

110

2026.02.03

植物大战僵尸版本入口地址汇总
植物大战僵尸版本入口地址汇总

本专题整合了植物大战僵尸版本入口地址汇总,前往文章中寻找想要的答案。

56

2026.02.03

c语言中/相关合集
c语言中/相关合集

本专题整合了c语言中/的用法、含义解释。阅读专题下面的文章了解更多详细内容。

9

2026.02.03

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
AngularJS教程
AngularJS教程

共24课时 | 3.3万人学习

CSS3实现按钮特效视频教程
CSS3实现按钮特效视频教程

共15课时 | 3.3万人学习

细说PHP第三季
细说PHP第三季

共58课时 | 11.4万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号