PHP XML解析类

简介:
Java代码   收藏代码
  1. <?php   
  2. /*  
  3.   +----------------------------------------------------------------------+  
  4.   | SofeeFramework for PHP 4                                             |  
  5.   +----------------------------------------------------------------------+  
  6.   | Copyright (c) 2004-2005 Sofee Development Team.(http://www.sofee.cn) |  
  7.   +----------------------------------------------------------------------+  
  8.   | This source file is subject to version 1.00 of the Sofee license,    |  
  9.   | that is bundled with this package in the file LICENSE, and is        |  
  10.   | available through the world-wide-web at the following url:           |  
  11.   | http://www.sofee.cn/license/1_00.txt.                                |  
  12.   | If you did not receive a copy of the Sofee license and are unable to |  
  13.   | obtain it through the world-wide-web, please send a note to          |  
  14.   | license@sofee.cn so we can mail you a copy immediately.              |  
  15.   +----------------------------------------------------------------------+  
  16.   | Author: Justin Wu <ezdevelop@gmail.com>                              |  
  17.   +----------------------------------------------------------------------+  
  18. */   
  19.        
  20. /* $Id: SofeeXmlParser.php,v 1.3 2005/05/30 06:30:14 wenlong Exp $ */   
  21.   
  22. /**  
  23. * Sofee XML Parser class - This is an XML parser based on PHP's "xml" extension.  
  24.  
  25. * The SofeeXmlParser class provides a very simple and easily usable toolset to convert XML   
  26. * to an array that can be processed with array iterators.  
  27.  
  28. * @package        SofeeFramework  
  29. * @access        public  
  30. * @version        $Revision: 1.1 $  
  31. * @author        Justin Wu <wenlong@php.net>  
  32. * @homepage        http://www.sofee.cn  
  33. * @copyright    Copyright (c) 2004-2005 Sofee Development Team.(http://www.sofee.cn)  
  34. * @since        2005-05-30  
  35. * @see            PEAR:XML_Parser | SimpleXML extension  
  36. */   
  37. class SofeeXmlParser {   
  38.        
  39.     /**  
  40.     * XML parser handle  
  41.     *  
  42.     * @var        resource  
  43.     * @see        xml_parser_create()  
  44.     */   
  45.     var $parser;   
  46.   
  47.     /**  
  48.     * source encoding  
  49.     *  
  50.     * @var        string  
  51.     */   
  52.     var $srcenc;   
  53.   
  54.     /**  
  55.     * target encoding  
  56.     *  
  57.     * @var        string  
  58.     */   
  59.     var $dstenc;   
  60.   
  61.     /**  
  62.     * the original struct  
  63.     *  
  64.     * @access    private  
  65.     * @var        array  
  66.     */   
  67.     var $_struct = array();   
  68.   
  69.     /**  
  70.     * Constructor  
  71.     *  
  72.     * @access        public  
  73.     * @param        mixed        [$srcenc] source encoding  
  74.     * @param        mixed        [$dstenc] target encoding  
  75.     * @return        void  
  76.     * @since          
  77.     */   
  78.     function SofeeXmlParser($srcenc = null, $dstenc = null) {   
  79.         $this->srcenc = $srcenc;   
  80.         $this->dstenc = $dstenc;   
  81.            
  82.         // initialize the variable.   
  83.         $this->parser = null;   
  84.         $this->_struct = array();   
  85.     }   
  86.   
  87.     /**  
  88.     * Free the resources  
  89.     *  
  90.     * @access        public  
  91.     * @return        void  
  92.     **/   
  93.     function free() {   
  94.         if (isset($this->parser) && is_resource($this->parser)) {   
  95.             xml_parser_free($this->parser);   
  96.             unset($this->parser);   
  97.         }   
  98.     }   
  99.   
  100.     /**  
  101.     * Parses the XML file  
  102.     *  
  103.     * @access        public  
  104.     * @param        string        [$file] the XML file name  
  105.     * @return        void  
  106.     * @since          
  107.     */   
  108.     function parseFile($file) {   
  109.         $data = @file_get_contents($file) or die("Can't open file $file for reading!");   
  110.         $this->parseString($data);   
  111.     }   
  112.   
  113.     /**  
  114.     * Parses a string.  
  115.     *  
  116.     * @access        public  
  117.     * @param        string        [$data] XML data  
  118.     * @return        void  
  119.     */   
  120.     function parseString($data) {   
  121.         if ($this->srcenc === null) {   
  122.             $this->parser = @xml_parser_create() or die('Unable to create XML parser resource.');   
  123.         } else {   
  124.             $this->parser = @xml_parser_create($this->srcenc) or die('Unable to create XML parser resource with '. $this->srcenc .' encoding.');   
  125.         }   
  126.            
  127.         if ($this->dstenc !== null) {   
  128.             @xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->dstenc) or die('Invalid target encoding');   
  129.         }   
  130.         xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);    // lowercase tags   
  131.         xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);        // skip empty tags   
  132.         if (!xml_parse_into_struct($this->parser, $data, &$this->_struct)) {   
  133.             printf("XML error: %s at line %d",    
  134.                     xml_error_string(xml_get_error_code($this->parser)),    
  135.                     xml_get_current_line_number($this->parser)   
  136.             );   
  137.             $this->free();   
  138.             exit();   
  139.         }   
  140.            
  141.         $this->_count = count($this->_struct);   
  142.         $this->free();   
  143.     }   
  144.   
  145.     /**  
  146.     * return the data struction  
  147.     *  
  148.     * @access        public  
  149.     * @return        array  
  150.     */   
  151.     function getTree() {   
  152.         $i = 0;   
  153.         $tree = array();   
  154.   
  155.         $tree = $this->addNode(   
  156.             $tree,    
  157.             $this->_struct[$i]['tag'],    
  158.             (isset($this->_struct[$i]['value'])) ? $this->_struct[$i]['value'] : '',    
  159.             (isset($this->_struct[$i]['attributes'])) ? $this->_struct[$i]['attributes'] : '',    
  160.             $this->getChild($i)   
  161.         );   
  162.   
  163.         unset($this->_struct);   
  164.         return ($tree);   
  165.     }   
  166.   
  167.     /**  
  168.     * recursion the children node data  
  169.     *  
  170.     * @access        public  
  171.     * @param        integer        [$i] the last struct index  
  172.     * @return        array  
  173.     */   
  174.     function getChild(&$i) {   
  175.         // contain node data   
  176.         $children = array();   
  177.   
  178.         // loop   
  179.         while (++$i < $this->_count) {   
  180.             // node tag name   
  181.             $tagname = $this->_struct[$i]['tag'];   
  182.             $value = isset($this->_struct[$i]['value']) ? $this->_struct[$i]['value'] : '';   
  183.             $attributes = isset($this->_struct[$i]['attributes']) ? $this->_struct[$i]['attributes'] : '';   
  184.   
  185.             switch ($this->_struct[$i]['type']) {   
  186.                 case 'open':   
  187.                     // node has more children   
  188.                     $child = $this->getChild($i);   
  189.                     // append the children data to the current node   
  190.                     $children = $this->addNode($children, $tagname, $value, $attributes, $child);   
  191.                     break;   
  192.                 case 'complete':   
  193.                     // at end of current branch   
  194.                     $children = $this->addNode($children, $tagname, $value, $attributes);   
  195.                     break;   
  196.                 case 'cdata':   
  197.                     // node has CDATA after one of it's children   
  198.                     $children['value'] .= $value;   
  199.                     break;   
  200.                 case 'close':   
  201.                     // end of node, return collected data    
  202.                     return $children;   
  203.                     break;   
  204.             }   
  205.            
  206.         }   
  207.         //return $children;   
  208.     }   
  209.   
  210.     /**  
  211.     * Appends some values to an array  
  212.     *  
  213.     * @access        public  
  214.     * @param        array        [$target]  
  215.     * @param        string        [$key]  
  216.     * @param        string        [$value]  
  217.     * @param        array        [$attributes]  
  218.     * @param        array        [$inner] the children  
  219.     * @return        void  
  220.     * @since          
  221.     */   
  222.     function addNode($target, $key, $value = '', $attributes = '', $child = '') {   
  223.         if (!isset($target[$key]['value']) && !isset($target[$key][0])) {   
  224.             if ($child != '') {   
  225.                 $target[$key] = $child;   
  226.             }   
  227.             if ($attributes != '') {   
  228.                 foreach ($attributes as $k => $v) {   
  229.                     $target[$key][$k] = $v;   
  230.                 }   
  231.             }   
  232.                
  233.             $target[$key]['value'] = $value;   
  234.         } else {   
  235.             if (!isset($target[$key][0])) {   
  236.                 // is string or other   
  237.                 $oldvalue = $target[$key];   
  238.                 $target[$key] = array();   
  239.                 $target[$key][0] = $oldvalue;   
  240.                 $index = 1;   
  241.             } else {   
  242.                 // is array   
  243.                 $index = count($target[$key]);   
  244.             }   
  245.   
  246.             if ($child != '') {   
  247.                 $target[$key][$index] = $child;   
  248.             }   
  249.   
  250.             if ($attributes != '') {   
  251.                 foreach ($attributes as $k => $v) {   
  252.                     $target[$key][$index][$k] = $v;   
  253.                 }   
  254.             }   
  255.             $target[$key][$index]['value'] = $value;   
  256.         }   
  257.         return $target;   
  258.     }   
  259.   
  260. }  
  261. ?>  

 实例一 (解析XML文件):

Java代码   收藏代码
  1. <?php  
  2. $file="http://dict.cn/ws.php?q=content";  
  3. require_once('SofeeXmlParser.php');  
  4. $xml = new SofeeXmlParser();  
  5. $xml->parseFile($file);   
  6. $tree = $xml->getTree();  
  7. unset($xml);  
  8. print "<pre>";  
  9. foreach($tree as $val){  
  10.     echo $val['key']['value'];  
  11.     echo $val['lang']['value'];  
  12. }  
  13. print "</pre>";  
  14. ?>  

实例二 (解析XML字符串):

Java代码   收藏代码
  1. <?php  
  2. $str = '<?xml version="1.0" encoding="gb2312"?>  
  3. <root>  
  4.   <info value="adevy">  
  5.     <name>adevy001</name>  
  6.     <sex>男</sex>  
  7.   </info>  
  8.   <info value="adevy">  
  9.     <name>adevy001</name>  
  10.     <sex>男</sex>  
  11.   </info>  
  12. </root>';  
  13. require_once('SofeeXmlParser.php');  
  14. $xml = new SofeeXmlParser();  
  15. $xml->parseString($str);  
  16. $tree = $xml->getTree();  
  17. unset($xml);  
  18. print "<pre>";  
  19. print_r($tree);  
  20. print "</pre>";  
  21. ?>   
相关文章
|
5月前
|
JSON 定位技术 PHP
PHP技巧:解析JSON及提取数据
这就是在PHP世界里探索JSON数据的艺术。这场狩猎不仅仅是为了获得数据,而是一种透彻理解数据结构的行动,让数据在你的编码海洋中畅游。通过这次冒险,你已经掌握了打开数据宝箱的钥匙。紧握它,让你在编程世界中随心所欲地航行。
175 67
|
8月前
|
存储 Java 文件存储
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— logback.xml 配置文件解析
本文解析了 `logback.xml` 配置文件的详细内容,包括日志输出格式、存储路径、控制台输出及日志级别等关键配置。通过定义 `LOG_PATTERN` 和 `FILE_PATH`,设置日志格式与存储路径;利用 `&lt;appender&gt;` 节点配置控制台和文件输出,支持日志滚动策略(如文件大小限制和保存时长);最后通过 `&lt;logger&gt;` 和 `&lt;root&gt;` 定义日志级别与输出方式。此配置适用于精细化管理日志输出,满足不同场景需求。
1948 1
|
8月前
|
Java 开发者
重学Java基础篇—Java类加载顺序深度解析
本文全面解析Java类的生命周期与加载顺序,涵盖从加载到卸载的七个阶段,并深入探讨初始化阶段的执行规则。通过单类、继承体系的实例分析,明确静态与实例初始化的顺序。同时,列举六种触发初始化的场景及特殊场景处理(如接口初始化)。提供类加载完整流程图与记忆口诀,助于理解复杂初始化逻辑。此外,针对空指针异常等问题提出排查方案,并给出最佳实践建议,帮助开发者优化程序设计、定位BUG及理解框架机制。最后扩展讲解类加载器层次与双亲委派机制,为深入研究奠定基础。
269 0
|
5月前
|
运维 监控 算法
局域网屏幕监控软件 PHP 图像块增量传输算法解析
本文探讨了一种基于PHP语言开发的图像块增量传输算法,适用于局域网屏幕监控场景。通过将屏幕图像分块处理、计算哈希值并对比变化区域,该算法显著降低了网络带宽占用,提升了监控效率。在企业管理和远程教育中,该技术可实现终端设备的实时监控与远程管控,同时支持与生物识别等技术融合,拓展应用范围。实验表明,该算法在常规办公场景下可减少90%以上的数据传输量,展现了良好的实时性和优化效果。
83 3
|
6月前
|
存储 监控 算法
内网监控桌面与 PHP 哈希算法:从数据追踪到行为审计的技术解析
本文探讨了内网监控桌面系统的技术需求与数据结构选型,重点分析了哈希算法在企业内网安全管理中的应用。通过PHP语言实现的SHA-256算法,可有效支持软件准入控制、数据传输审计及操作日志存证等功能。文章还介绍了性能优化策略(如分块哈希计算和并行处理)与安全增强措施(如盐值强化和动态更新),并展望了哈希算法在图像处理、网络流量分析等领域的扩展应用。最终强调了构建完整内网安全闭环的重要性,为企业数字资产保护提供技术支撑。
155 2
|
8月前
|
XML JavaScript Android开发
【Android】网络技术知识总结之WebView,HttpURLConnection,OKHttp,XML的pull解析方式
本文总结了Android中几种常用的网络技术,包括WebView、HttpURLConnection、OKHttp和XML的Pull解析方式。每种技术都有其独特的特点和适用场景。理解并熟练运用这些技术,可以帮助开发者构建高效、可靠的网络应用程序。通过示例代码和详细解释,本文为开发者提供了实用的参考和指导。
222 15
|
8月前
|
存储 监控 安全
重学Java基础篇—类的生命周期深度解析
本文全面解析了Java类的生命周期,涵盖加载、验证、准备、解析、初始化、使用及卸载七个关键阶段。通过分阶段执行机制详解(如加载阶段的触发条件与技术实现),结合方法调用机制、内存回收保护等使用阶段特性,以及卸载条件和特殊场景处理,帮助开发者深入理解JVM运作原理。同时,文章探讨了性能优化建议、典型异常处理及新一代JVM特性(如元空间与模块化系统)。总结中强调安全优先、延迟加载与动态扩展的设计思想,并提供开发建议与进阶方向,助力解决性能调优、内存泄漏排查及框架设计等问题。
323 5
|
8月前
|
安全 IDE Java
重学Java基础篇—Java Object类常用方法深度解析
Java中,Object类作为所有类的超类,提供了多个核心方法以支持对象的基本行为。其中,`toString()`用于对象的字符串表示,重写时应包含关键信息;`equals()`与`hashCode()`需成对重写,确保对象等价判断的一致性;`getClass()`用于运行时类型识别;`clone()`实现对象复制,需区分浅拷贝与深拷贝;`wait()/notify()`支持线程协作。此外,`finalize()`已过时,建议使用更安全的资源管理方式。合理运用这些方法,并遵循最佳实践,可提升代码质量与健壮性。
227 1
|
8月前
|
存储 监控 算法
关于员工上网监控系统中 PHP 关联数组算法的学术解析
在当代企业管理中,员工上网监控系统是维护信息安全和提升工作效率的关键工具。PHP 中的关联数组凭借其灵活的键值对存储方式,在记录员工网络活动、管理访问规则及分析上网行为等方面发挥重要作用。通过关联数组,系统能高效记录每位员工的上网历史,设定网站访问权限,并统计不同类型的网站访问频率,帮助企业洞察员工上网模式,发现潜在问题并采取相应管理措施,从而保障信息安全和提高工作效率。
111 7
|
8月前
|
传感器 监控 Java
Java代码结构解析:类、方法、主函数(1分钟解剖室)
### Java代码结构简介 掌握Java代码结构如同拥有程序世界的建筑蓝图,类、方法和主函数构成“黄金三角”。类是独立的容器,承载成员变量和方法;方法实现特定功能,参数控制输入环境;主函数是程序入口。常见错误包括类名与文件名不匹配、忘记static修饰符和花括号未闭合。通过实战案例学习电商系统、游戏角色控制和物联网设备监控,理解类的作用、方法类型和主函数任务,避免典型错误,逐步提升编程能力。 **脑图速记法**:类如太空站,方法即舱段;main是发射台,static不能换;文件名对仗,括号要成双;参数是坐标,void不返航。
307 5

热门文章

最新文章

推荐镜像

更多
  • DNS