`
hudeyong926
  • 浏览: 2028422 次
  • 来自: 武汉
社区版块
存档分类
最新评论

PHP XML解析类

阅读更多
<?php 
/* 
  +----------------------------------------------------------------------+ 
  | SofeeFramework for PHP 4                                             | 
  +----------------------------------------------------------------------+ 
  | Copyright (c) 2004-2005 Sofee Development Team.(http://www.sofee.cn) | 
  +----------------------------------------------------------------------+ 
  | This source file is subject to version 1.00 of the Sofee license,    | 
  | that is bundled with this package in the file LICENSE, and is        | 
  | available through the world-wide-web at the following url:           | 
  | http://www.sofee.cn/license/1_00.txt.                                | 
  | If you did not receive a copy of the Sofee license and are unable to | 
  | obtain it through the world-wide-web, please send a note to          | 
  | license@sofee.cn so we can mail you a copy immediately.              | 
  +----------------------------------------------------------------------+ 
  | Author: Justin Wu <ezdevelop@gmail.com>                              | 
  +----------------------------------------------------------------------+ 
*/ 
     
/* $Id: SofeeXmlParser.php,v 1.3 2005/05/30 06:30:14 wenlong Exp $ */ 

/** 
* Sofee XML Parser class - This is an XML parser based on PHP's "xml" extension. 
* 
* The SofeeXmlParser class provides a very simple and easily usable toolset to convert XML  
* to an array that can be processed with array iterators. 
* 
* @package        SofeeFramework 
* @access        public 
* @version        $Revision: 1.1 $ 
* @author        Justin Wu <wenlong@php.net> 
* @homepage        http://www.sofee.cn 
* @copyright    Copyright (c) 2004-2005 Sofee Development Team.(http://www.sofee.cn) 
* @since        2005-05-30 
* @see            PEAR:XML_Parser | SimpleXML extension 
*/ 
class SofeeXmlParser { 
     
    /** 
    * XML parser handle 
    * 
    * @var        resource 
    * @see        xml_parser_create() 
    */ 
    var $parser; 

    /** 
    * source encoding 
    * 
    * @var        string 
    */ 
    var $srcenc; 

    /** 
    * target encoding 
    * 
    * @var        string 
    */ 
    var $dstenc; 

    /** 
    * the original struct 
    * 
    * @access    private 
    * @var        array 
    */ 
    var $_struct = array(); 

    /** 
    * Constructor 
    * 
    * @access        public 
    * @param        mixed        [$srcenc] source encoding 
    * @param        mixed        [$dstenc] target encoding 
    * @return        void 
    * @since         
    */ 
    function SofeeXmlParser($srcenc = null, $dstenc = null) { 
        $this->srcenc = $srcenc; 
        $this->dstenc = $dstenc; 
         
        // initialize the variable. 
        $this->parser = null; 
        $this->_struct = array(); 
    } 

    /** 
    * Free the resources 
    * 
    * @access        public 
    * @return        void 
    **/ 
    function free() { 
        if (isset($this->parser) && is_resource($this->parser)) { 
            xml_parser_free($this->parser); 
            unset($this->parser); 
        } 
    } 

    /** 
    * Parses the XML file 
    * 
    * @access        public 
    * @param        string        [$file] the XML file name 
    * @return        void 
    * @since         
    */ 
    function parseFile($file) { 
        $data = @file_get_contents($file) or die("Can't open file $file for reading!"); 
        $this->parseString($data); 
    } 

    /** 
    * Parses a string. 
    * 
    * @access        public 
    * @param        string        [$data] XML data 
    * @return        void 
    */ 
    function parseString($data) { 
        if ($this->srcenc === null) { 
            $this->parser = @xml_parser_create() or die('Unable to create XML parser resource.'); 
        } else { 
            $this->parser = @xml_parser_create($this->srcenc) or die('Unable to create XML parser resource with '. $this->srcenc .' encoding.'); 
        } 
         
        if ($this->dstenc !== null) { 
            @xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->dstenc) or die('Invalid target encoding'); 
        } 
        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);    // lowercase tags 
        xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);        // skip empty tags 
        if (!xml_parse_into_struct($this->parser, $data, &$this->_struct)) { 
            printf("XML error: %s at line %d",  
                    xml_error_string(xml_get_error_code($this->parser)),  
                    xml_get_current_line_number($this->parser) 
            ); 
            $this->free(); 
            exit(); 
        } 
         
        $this->_count = count($this->_struct); 
        $this->free(); 
    } 

    /** 
    * return the data struction 
    * 
    * @access        public 
    * @return        array 
    */ 
    function getTree() { 
        $i = 0; 
        $tree = array(); 

        $tree = $this->addNode( 
            $tree,  
            $this->_struct[$i]['tag'],  
            (isset($this->_struct[$i]['value'])) ? $this->_struct[$i]['value'] : '',  
            (isset($this->_struct[$i]['attributes'])) ? $this->_struct[$i]['attributes'] : '',  
            $this->getChild($i) 
        ); 

        unset($this->_struct); 
        return ($tree); 
    } 

    /** 
    * recursion the children node data 
    * 
    * @access        public 
    * @param        integer        [$i] the last struct index 
    * @return        array 
    */ 
    function getChild(&$i) { 
        // contain node data 
        $children = array(); 

        // loop 
        while (++$i < $this->_count) { 
            // node tag name 
            $tagname = $this->_struct[$i]['tag']; 
            $value = isset($this->_struct[$i]['value']) ? $this->_struct[$i]['value'] : ''; 
            $attributes = isset($this->_struct[$i]['attributes']) ? $this->_struct[$i]['attributes'] : ''; 

            switch ($this->_struct[$i]['type']) { 
                case 'open': 
                    // node has more children 
                    $child = $this->getChild($i); 
                    // append the children data to the current node 
                    $children = $this->addNode($children, $tagname, $value, $attributes, $child); 
                    break; 
                case 'complete': 
                    // at end of current branch 
                    $children = $this->addNode($children, $tagname, $value, $attributes); 
                    break; 
                case 'cdata': 
                    // node has CDATA after one of it's children 
                    $children['value'] .= $value; 
                    break; 
                case 'close': 
                    // end of node, return collected data  
                    return $children; 
                    break; 
            } 
         
        } 
        //return $children; 
    } 

    /** 
    * Appends some values to an array 
    * 
    * @access        public 
    * @param        array        [$target] 
    * @param        string        [$key] 
    * @param        string        [$value] 
    * @param        array        [$attributes] 
    * @param        array        [$inner] the children 
    * @return        void 
    * @since         
    */ 
    function addNode($target, $key, $value = '', $attributes = '', $child = '') { 
        if (!isset($target[$key]['value']) && !isset($target[$key][0])) { 
            if ($child != '') { 
                $target[$key] = $child; 
            } 
            if ($attributes != '') { 
                foreach ($attributes as $k => $v) { 
                    $target[$key][$k] = $v; 
                } 
            } 
             
            $target[$key]['value'] = $value; 
        } else { 
            if (!isset($target[$key][0])) { 
                // is string or other 
                $oldvalue = $target[$key]; 
                $target[$key] = array(); 
                $target[$key][0] = $oldvalue; 
                $index = 1; 
            } else { 
                // is array 
                $index = count($target[$key]); 
            } 

            if ($child != '') { 
                $target[$key][$index] = $child; 
            } 

            if ($attributes != '') { 
                foreach ($attributes as $k => $v) { 
                    $target[$key][$index][$k] = $v; 
                } 
            } 
            $target[$key][$index]['value'] = $value; 
        } 
        return $target; 
    } 

}
?>

 实例一 (解析XML文件):

<?php
$file="http://dict.cn/ws.php?q=content";
require_once('SofeeXmlParser.php');
$xml = new SofeeXmlParser();
$xml->parseFile($file); 
$tree = $xml->getTree();
unset($xml);
print "<pre>";
foreach($tree as $val){
	echo $val['key']['value'];
	echo $val['lang']['value'];
}
print "</pre>";
?>

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

<?php
$str = '<?xml version="1.0" encoding="gb2312"?>
<root>
  <info value="adevy">
    <name>adevy001</name>
    <sex>男</sex>
  </info>
  <info value="adevy">
    <name>adevy001</name>
    <sex>男</sex>
  </info>
</root>';
require_once('SofeeXmlParser.php');
$xml = new SofeeXmlParser();
$xml->parseString($str);
$tree = $xml->getTree();
unset($xml);
print "<pre>";
print_r($tree);
print "</pre>";
?> 
 

 

分享到:
评论

相关推荐

    php xml解析类

    本文将详细探讨PHP中的XML解析类,并结合“php xml解析类”这一主题,分享相关的知识点。 首先,PHP提供了两种主要的XML解析方式:DOM(Document Object Model)和SimpleXML。DOM解析器提供了完整的XML文档对象模型...

    php中用来解析xml的类

    本篇文章将详细介绍一个PHP XML解析类的使用,以及如何通过该类来解析XML文件。 首先,我们要了解PHP提供的XML解析方法。PHP提供了两种主要的XML解析方式:DOM(Document Object Model)和SAX(Simple API for XML...

    php解析xml实例

    php解析xml实例php解析xml实例php解析xml实例php解析xml实例php解析xml实例php解析xml实例php解析xml实例php解析xml实例php解析xml实例php解析xml实例php解析xml实例php解析xml实例

    php快速解析xml

    php快速解析xml已经试过,很好用。内赋了简单的使用方法,可以仿照例子进行解析。

    PHP5中XML解析的应用改进.pdf

    本文讨论了PHP中对XML解析的支持,分析了PHP的XML解析器Expat的工作过程,同时提出直接利用扩展DOM类来完成XML文档操作。文中的实例结果也表现了PHP对XML应用支持的灵活性。 PHP5中XML解析的应用改进的优点有: ...

    php递归解析xml

    本篇将详细介绍如何使用PHP的递归方法解析XML并将其转换为数组,以便在ExtJS的tree组件中使用。 首先,我们来讨论如何使用SimpleXML扩展来解析XML。SimpleXML是一个易于使用的接口,可将XML字符串或文件加载为PHP...

    php 实现post xml并解析

    在PHP中创建XML数据,可以使用`DOMDocument`类。首先,实例化`DOMDocument`对象,然后使用`createElement`方法创建元素节点,`nodeValue`设置文本内容,最后用`saveXML`方法将整个文档转换为字符串。 ```php $...

    PHP操作xml类

    首先,我们有一个名为"xml.php"的类文件,这个类可能是对PHP内置的DOMDocument或SimpleXMLElement类进行了封装,以便更方便地进行XML处理。在"index.php"中,我们可以看到这个XML类的具体使用示例,而"index.xml"则...

    PHP XML操作的各种方法解析(比较详细)

    ### PHP XML操作的各种方法解析 #### 一、XML简介及特点 XML(可扩展标记语言,eXtensible Markup Language)是一种类似于HTML的标记语言,但它的用途与HTML有着本质的区别。HTML主要用于定义网页的表现形式,而...

    php读取xml文件类

    PHP提供了DOMDocument类,这是一个强大的工具,可以用来解析、修改和操作XML文档。下面将详细讨论PHP如何利用DOMDocument类读取XML文件以及这个“php读取xml文件类”的基本工作原理。 首先,DOMDocument类是PHP内建...

    php解析xml文档

    其中,SimpleXML是PHP提供的一个非常简单易用的XML解析扩展,它允许开发者以面向对象的方式来处理XML文档。下面我们将主要使用SimpleXML进行示例。 1. **加载XML文档** 使用`simplexml_load_file()`函数可以加载...

    php xml转数组

    首先,PHP提供了内置的`DOMDocument`类和`DOMXpath`类,它们可以用来解析XML文档并提取数据。以下是一个基本的转换过程: 1. **创建DOMDocument对象**: ```php $xmlString = '&lt;root&gt;&lt;item id="1"&gt;Item 1&lt;/item&gt;...

    一个用来解析XML文档的类

    - 使用PHP内置的XML解析函数`xml_parse_into_struct()`来解析XML文件,并将结果存储在数组`$vals`中。 - 遍历解析后的结果,构建嵌套数组`$this-&gt;params`,其中包含了原始XML文件的结构化表示。 ##### 实现细节 1....

    PHP实现XML与数据格式进行转换类

    类设计时应考虑错误处理,如XML解析错误、无效的数据转换、文件读写异常等。还可能包括XML命名空间、属性、注释等高级特性的支持。 5. **实际应用** 这种XML转换类在多种场景下都非常有用,例如: - 数据交换:...

    PHP对XML的解析

    无论是对于初学者还是有经验的开发者,掌握PHP中的XML解析技巧都是非常有价值的。它不仅提高了数据处理的效率,还增强了程序的灵活性和可维护性。在现代Web开发中,理解并熟练运用PHP与XML的交互操作,将使开发者...

    PHP 读取 Android APK XML文件,无需JDK

    3. **解析XML内容**:获取到XML文件内容后,我们可以使用PHP的DOMDocument和DOMXpath类来解析XML。这将帮助我们提取出所需的数据。 ```php $doc = new DOMDocument(); @$doc-&gt;loadXML($xmlContent); // '@' 用于...

    ajaxfileupload上传及解析xml

    本教程将详细讲解如何使用AjaxFileUpload插件上传XML文件,并且解析XML内容。 首先,我们需要了解jQuery库。jQuery是一个强大的JavaScript库,简化了DOM操作、事件处理、动画效果以及AJAX交互。在本示例中,jQuery...

    PHP生成XML的类

    - **$parser**:XML解析器对象。 - **$vals**:XML解析后的值数组。 - **$index**:节点索引数组,用于快速定位特定节点的位置。 - **$dbtable_array**:指定 `$dbtable` 的节点位置。 - **$array**:存储解析后节点...

    PHP XML Expat 解析器.md

    ### PHP XML Expat 解析...**总结**:Expat解析器作为一种高效的XML解析工具,适用于需要处理大量XML数据的应用场景。通过对回调函数的设置,开发者能够灵活地控制XML文档的解析过程,从而实现对数据的有效处理和利用。

Global site tag (gtag.js) - Google Analytics