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


Posted in PHP onJuly 29, 2015

本文实例讲述了PHP实现XML与数据格式进行转换类。分享给大家供大家参考。具体如下:

<?php
/**
 * xml2array() will convert the given XML text to an array in the XML structure. 
 * Link: http://www.bin-co.com/php/scripts/xml2array/ 
 * Arguments : $contents - The XML text 
 * $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value. 
 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure. 
 * Examples: $array = xml2array(file_get_contents('feed.xml')); 
 * $array = xml2array(file_get_contents('feed.xml', 1, 'attribute'));
 */
function xml2array($contents, $get_attributes = 1, $priority = 'tag') {
  if (!$contents) return array();
  if (!function_exists('xml_parser_create')) {
    // print "'xml_parser_create()' function not found!";
    return array();
  } 
  // Get the XML parser of PHP - PHP must have this module for the parser to work
  $parser = xml_parser_create('');
  xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss 
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, trim($contents), $xml_values);
  xml_parser_free($parser);
  if (!$xml_values) return; //Hmm... 
  // Initializations
  $xml_array = array();
  $parents = array();
  $opened_tags = array();
  $arr = array();
  $current = &$xml_array; //Refference 
  // Go through the tags.
  $repeated_tag_index = array(); //Multiple tags with same name will be turned into an array 
  foreach($xml_values as $data) {
    unset($attributes, $value); //Remove existing values, or there will be trouble 
    // This command will extract these variables into the foreach scope
    // tag(string), type(string), level(int), attributes(array).
    extract($data); //We could use the array by itself, but this cooler. 
    $result = array();
    $attributes_data = array();
    if (isset($value)) {
      if ($priority == 'tag') $result = $value;
      else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode 
    } 
    // Set the attributes too.
    if (isset($attributes) and $get_attributes) {
      foreach($attributes as $attr => $val) {
        if ($priority == 'tag') $attributes_data[$attr] = $val;
        else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' 
      } 
    } 
    // See tag status and do the needed.
    if ($type == "open") { // The starting of the tag '<tag>'
      $parent[$level-1] = &$current;
      if (!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
        $current[$tag] = $result;
        if ($attributes_data) $current[$tag . '_attr'] = $attributes_data;
        $repeated_tag_index[$tag . '_' . $level] = 1;
        $current = &$current[$tag];
      } else { // There was another element with the same tag name
        if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
          $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
          $repeated_tag_index[$tag . '_' . $level]++;
        } else { // This section will make the value an array if multiple tags with the same name appear together
          $current[$tag] = array($current[$tag], $result); //This will combine the existing item and the new item together to make an array 
          $repeated_tag_index[$tag . '_' . $level] = 2;
          if (isset($current[$tag . '_attr'])) { // The attribute of the last(0th) tag must be moved as well
            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
            unset($current[$tag . '_attr']);
          } 
        } 
        $last_item_index = $repeated_tag_index[$tag . '_' . $level]-1;
        $current = &$current[$tag][$last_item_index];
      } 
    } elseif ($type == "complete") { // Tags that ends in 1 line '<tag />'
      // See if the key is already taken.
      if (!isset($current[$tag])) { // New Key
        $current[$tag] = $result;
        $repeated_tag_index[$tag . '_' . $level] = 1;
        if ($priority == 'tag' and $attributes_data) $current[$tag . '_attr'] = $attributes_data;
      } else { // If taken, put all things inside a list(array)
        if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
          // ...push the new element into that array.
          $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
          if ($priority == 'tag' and $get_attributes and $attributes_data) {
            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
          } 
          $repeated_tag_index[$tag . '_' . $level]++;
        } else { // If it is not an array...
          $current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value 
          $repeated_tag_index[$tag . '_' . $level] = 1;
          if ($priority == 'tag' and $get_attributes) {
            if (isset($current[$tag . '_attr'])) { // The attribute of the last(0th) tag must be moved as well
              $current[$tag]['0_attr'] = $current[$tag . '_attr'];
              unset($current[$tag . '_attr']);
            } 
            if ($attributes_data) {
              $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
            } 
          } 
          $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken 
        } 
      } 
    } elseif ($type == 'close') { // End of tag '</tag>'
      $current = &$parent[$level-1];
    } 
  } 
  return($xml_array);
} 
// Array to XML
class array2xml {
  public $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  public $sub_item = array();
  public function __construct($array) {
    $sub_item = array();
    $this->output .= $this->xmlmake($array);
  } 
  public function xmlmake($array, $fk = '') {
    $xml = '';
    global $sub_item;
    foreach ($array as $key => $value) {
      if (is_array($value)) {
        if (is_numeric($key)) {
          $this->sub_item=array_merge($this->sub_item,array($fk));
          $xml .= "<{$fk}>" . $this->xmlmake($value, $key) . "</{$fk}>";
        } else {
          $xml .= "<{$key}>" . $this->xmlmake($value, $key) . "</{$key}>";
        } 
      } else {
        $xml .= "<{$key}>{$value}</{$key}>\n";
      } 
    } 
    return $xml;
  } 
  public function output(){
    foreach($this->sub_item as $t){
      $this->output = str_replace("<{$t}><{$t}>","<{$t}>",$this->output);
      $this->output = str_replace("</{$t}></{$t}>","</{$t}>",$this->output);
    }
    return $this->output;
  }
}

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

PHP 相关文章推荐
安装APACHE
Jan 15 PHP
精通php的十大要点(上)
Feb 04 PHP
pdo中使用参数化查询sql
Aug 11 PHP
php preg_filter执行一个正则表达式搜索和替换
Feb 27 PHP
php中使用接口实现工厂设计模式的代码
Jun 17 PHP
基于PHP实现商品成交时发送短信功能
May 11 PHP
PHP开发中csrf攻击的简单演示和防范
May 07 PHP
PHP 7安装调试工具Xdebug扩展的方法教程
Jun 17 PHP
详解php实现页面静态化原理
Jun 21 PHP
针对thinkPHP5框架存储过程bug重写的存储过程扩展类完整实例
Jun 16 PHP
PHP如何通过表单直接提交大文件详解
Jan 08 PHP
Laravel5.5 数据库迁移:创建表与修改表示例
Oct 23 PHP
PHP获取某个月最大天数(最后一天)的方法
Jul 29 #PHP
discuz图片顺序混乱解决方案
Jul 29 #PHP
php计算title标题相似比的方法
Jul 29 #PHP
PHP实现简单实用的验证码类
Jul 29 #PHP
php使用gzip压缩传输js和css文件的方法
Jul 29 #PHP
PHP实现加强版加密解密类实例
Jul 29 #PHP
PHP之密码加密的几种方式
Jul 29 #PHP
You might like
过滤掉PHP数组中的重复值的实现代码
2011/07/17 PHP
php字符串分割函数explode的实例代码
2013/02/07 PHP
orm获取关联表里的属性值
2016/04/17 PHP
php 微信公众平台开发模式实现多客服的实例代码
2016/11/07 PHP
window.location和document.location的区别分析
2008/12/23 Javascript
Javascript封装DOMContentLoaded事件实例
2014/06/12 Javascript
javascript自定义函数参数传递为字符串格式
2014/07/29 Javascript
jquery实现在网页指定区域显示自定义右键菜单效果
2015/08/25 Javascript
使用Sticky组件实现带sticky效果的tab导航和滚动导航的方法
2016/03/22 Javascript
js控制台输出的方法(详解)
2016/11/26 Javascript
完美实现js焦点轮播效果(一)
2017/03/07 Javascript
bootstrap table单元格新增行并编辑
2017/05/19 Javascript
Angular排序实例详解
2017/06/28 Javascript
使用travis-ci如何持续部署node.js应用详解
2017/07/30 Javascript
微信小程序的日期选择器的实例详解
2017/09/29 Javascript
Node.js 多线程完全指南总结
2019/03/27 Javascript
js实现for循环跳过undefined值示例
2019/07/02 Javascript
layer关闭弹出窗口触发表单提交问题的处理方法
2019/09/25 Javascript
通过高德地图API获得某条道路上的所有坐标用于描绘道路的方法
2020/08/24 Javascript
Python实现的多线程http压力测试代码
2017/02/08 Python
python3制作捧腹网段子页爬虫
2017/02/12 Python
python matplotlib 注释文本箭头简单代码示例
2018/01/08 Python
python re.sub()替换正则的匹配内容方法
2019/07/22 Python
Goodee官方商店:迷你投影仪
2021/03/15 全球购物
师范应届毕业生自荐信
2013/11/18 职场文书
大学三年的自我评价
2013/12/25 职场文书
军训自我鉴定范文
2014/02/13 职场文书
应届毕业生自荐书
2014/06/18 职场文书
国际贸易求职信
2014/07/05 职场文书
儿园租房协议书范本
2014/12/02 职场文书
公司保密管理制度
2015/08/04 职场文书
学生会部长竞选稿
2015/11/19 职场文书
反四风问题学习心得体会
2016/01/22 职场文书
python OpenCV学习笔记
2021/03/31 Python
深入浅出的讲解:信号调制到底是如何实现的
2022/02/18 无线电
python如何将mat文件转为png
2022/07/15 Python