PHP解析xml格式数据工具类示例

本文实例讲述了PHP解析xml格式数据工具类。分享给大家供大家参考,具体如下:

class ome_xml {
  /**
  * xml资源
  *
  * @var    resource
  * @see    xml_parser_create()
  */
  public $parser;
  /**
  * 资源编码
  *
  * @var    string
  */
  public $srcenc;
  /**
  * target encoding
  *
  * @var    string
  */
  public $dstenc;
  /**
  * the original struct
  *
  * @access  private
  * @var    array
  */
  public $_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();
  }
  /**
  * Parses the XML file
  *
  * @access    public
  * @param    string    [$file] the XML file name
  * @return    void
  * @since
  */
  function xml2array($file) {
    //$this->SofeeXmlParser('utf-8');
  $data = file_get_contents($file);
    $this->parseString($data);
    return $this->getTree();
  }
  function xml3array($file){
  $data = file_get_contents($file);
  $this->parseString($data);
  return $this->_struct;
  }
  /**
  * Parses a string.
  *
  * @access    public
  * @param    string    data XML data
  * @return    void
  */
  function parseString($data) {
    if ($this->srcenc === null) {
      $this->parser = xml_parser_create();
    } else {
      if($this->parser = xml_parser_create($this->srcenc)) {
        return '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();
      return false;
    }
    $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;
  }
  /**
  * 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);
    }
  }
}

PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XML:
http://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress

XML代码在线格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP针对XML文件操作技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《PHP错误与异常处理方法总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

(0)

相关推荐

  • php解析xml方法实例详解

    本文以实例形式详细讲述了php解析xml方法.分享给大家供大家参考.具体分析如下: books.xml文件如下: <?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book category="children"> <title lang="en">Harry Potter</title> <aut

  • PHP用SAX解析XML的实现代码与问题分析

    复制代码 代码如下: <?php $g_books = array(); $g_elem = null; function startElement( $parser, $name, $attrs ) { global $g_books, $g_elem; if ( $name == 'BOOK' ) $g_books []= array(); $g_elem = $name; } function endElement( $parser, $name ) { global $g_elem; $

  • PHP 以POST方式提交XML、获取XML,解析XML详解及实例

    PHP 以POST方式提交XML.获取XML,最后解析XML 以POST方式提交XML // Do a POST $data="<?xml version='1.0' encoding='UTF-8'?> <TypeRsp> <CONNECT_ID>1</CONNECT_ID> <MO_MESSAGE_ID>2</MO_MESSAGE_ID> </TypeRsp>"; //$data = array('

  • 使用PHP DOM-XML创建和解析XML文件

    使用PHP DOM-XML创建和解析XML文件 <?php    /**   * Topic:       Create and parse XML files using PHP DOM-XML   * Source:      http://www.php.net/domxml   * Reference:   http://www.zugeschaut-und-mitgebaut.de/php/extension.domxml.html   * Author:      urs@circl

  • PHP基于SimpleXML生成和解析xml的方法示例

    本文实例讲述了PHP基于SimpleXML生成和解析xml的方法.分享给大家供大家参考,具体如下: xml就不多解释了,php也提供了操作xml的方法,php操作xml可以有多种方式如domdocment,simplexml,xmlwriter等其中最简单的应该是simplexml了,这次就来说说simplexml怎么读取和解析xml文件或字符串 1. 生成xml字符串和文件 <?php header("Content-type: text/html; charset=utf-8"

  • php遍历解析xml字符串的方法

    本文实例讲述了php遍历解析xml字符串的方法.分享给大家供大家参考,具体如下: <?php $content = <<<XML <?xml version="1.0" encoding="UTF-8"?> <test> <global_setting> <ping_protocol>HTTP</ping_protocol> <ping_port>80</ping_

  • php解析xml 的四种简单方法(附实例)

    XML处理是开发过程中经常遇到的,PHP对其也有很丰富的支持,本文只是对其中某几种解析技术做简要说明,包括:Xml parser, SimpleXML, XMLReader, DOMDocument. 1. XML Expat Parser: XML Parser使用Expat XML解析器.Expat是一种基于事件的解析器,它把XML文档视为一系列事件.当某个事件发生时,它调用一个指定的函数处理它.Expat是无验证的解析器,忽略任何链接到文档的DTD.但是,如果文档的形式不好,则会以一个错误

  • PHP使用xpath解析XML的方法详解

    本文实例讲述了PHP使用xpath解析XML的方法.分享给大家供大家参考,具体如下: XML文件在PHP网站开发的轻量级应用中使用非常广泛,而PHP解析和读取XML文件的方式有很多种,比如JS DOM.SimpleXml.Xpath等方式解析XML文件,今天来讲讲在PHP中使用Xpath解析XML的实例,同时通过Xpath解析XML的实例来介绍部分基础的Xpath语法. Xpath是什么? Xapth主要用来在XML文档中查询信息的工具,通过使用路径表达式可以解析XML文件,读取XML文件中的数

  • PHP4和PHP5版本下解析XML文档的操作方法实例分析

    本文实例讲述了PHP4和PHP5版本下解析XML文档的操作方法.分享给大家供大家参考,具体如下: 在PHP网站开发与建设过程中,时常会碰到需要对XML文档进行解析,PHP4版本自带了XML解析器(sax),PHP5版本增加了SimpleXML(基于dom)的XML扩展,对XML的解析更是非常方便,今天和大家分享下在不同环境下对XML文档进行解析的方法. XML文档 <?xml version="1.0" encoding="gbk"?> <Leap

  • php 解析xml 的四种方法详细介绍

    php 解析xml 的四种方法 XML处理是开发过程中经常遇到的,PHP对其也有很丰富的支持,本文只是对其中某几种解析技术做简要说明,包括:Xml parser, SimpleXML, XMLReader, DOMDocument. 1. XML Expat Parser: XML Parser使用Expat XML解析器.Expat是一种基于事件的解析器,它把XML文档视为一系列事件.当某个事件发生时,它调用一个指定的函数处理它.Expat是无验证的解析器,忽略任何链接到文档的DTD.但是,如

  • PHP基于DOMDocument解析和生成xml的方法分析

    本文实例讲述了PHP基于DOMDocument解析和生成xml的方法.分享给大家供大家参考,具体如下: 前面和大家分享了SimpleXML操作xml的一些知识,但是php中除了simplexml还有DOMDocument,这次就着重来看看DOMDocument的用法,还是把生成xml和解析xml分开写 1. xml的生成 DOMDocument操作xml要比先前的simplexml要复杂一点,我觉得simplexml就想Java里的dom4j,不管怎样原理都是一样的.如果把DOMDocument

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

    XML是一种流行的半结构化文件格式,以一种类似数据库的格式存储数据.在实际应用中,一些简单的.安全性较低的数据往往使用 XML文件的格式进行存储.这样做的好处一方面可以通过减少与数据库的交互性操作提高读取效率,另一方面可以有效利用 XML的优越性降低程序的编写难度. PHP提供了一整套的读取 XML文件的方法,很容易的就可以编写基于 XML的脚本程序.本章将要介绍 PHP与 XML的操作方法,并对几个常用的 XML类库做一些简要介绍. 1 XML简介 XML是"可扩展性标识语言(eXtensib

随机推荐