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 相关文章推荐
PHP学习之整理字符串
Apr 17 PHP
PHP 第二节 数据类型之数组
Apr 28 PHP
phpadmin如何导入导出大数据文件及php.ini参数修改
Feb 18 PHP
PHP数据类型之布尔型的介绍
Apr 28 PHP
解析thinkphp基本配置 convention.php
Jun 18 PHP
php防止CC攻击代码 php防止网页频繁刷新
Dec 21 PHP
浅谈PHP中关于foreach使用引用变量的坑
Nov 14 PHP
自制PHP框架之路由与控制器
May 07 PHP
PHP jQuery+Ajax结合写批量删除功能
May 19 PHP
PHP 中TP5 Request 请求对象的实例详解
Jul 31 PHP
laravel5.6实现数值转换
Oct 23 PHP
在 Laravel 6 中缓存数据库查询结果的方法
Dec 11 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个人网站架设连环讲(一)
2006/10/09 PHP
PHP根据传来的16进制颜色代码自动改变背景颜色
2014/06/13 PHP
PHP定时执行任务实现方法详解(Timer)
2015/07/30 PHP
TNC vs IO BO3 第二场2.13
2021/03/10 DOTA
javascript String 的扩展方法集合
2008/06/01 Javascript
javascript中删除指定数组中指定的元素的代码
2011/02/12 Javascript
js中function()使用方法
2013/12/24 Javascript
jQuery的live()方法对hover事件的处理示例
2014/02/27 Javascript
基于Jquery代码实现手风琴菜单
2015/11/19 Javascript
JavaScript使用DeviceOne开发实战(三)仿微信应用
2015/12/02 Javascript
通过node-mysql搭建Windows+Node.js+MySQL环境的教程
2016/03/01 Javascript
第十篇BootStrap轮播插件使用详解
2016/06/21 Javascript
javascript时间差插件分享
2016/07/18 Javascript
Angularjs添加排序查询功能的实例代码
2017/10/24 Javascript
解决vue页面刷新或者后退参数丢失的问题
2018/03/13 Javascript
JS实现的哈夫曼编码示例【原始版与修改版】
2018/04/22 Javascript
jQuery.extend 与 jQuery.fn.extend的用法及区别实例分析
2018/07/25 jQuery
微信小程序使用wxParse解析html的实现示例
2018/08/30 Javascript
微信小程序实现炫酷的弹出式菜单特效
2019/01/28 Javascript
vue中created和mounted的区别浅析
2019/08/13 Javascript
Python使用稀疏矩阵节省内存实例
2014/06/27 Python
python获取文件真实链接的方法,针对于302返回码
2018/05/14 Python
python模块smtplib学习
2018/05/22 Python
python中的print()输出
2019/04/12 Python
python绘制雪景图
2019/12/16 Python
python可以用哪些数据库
2020/06/22 Python
python 多线程死锁问题的解决方案
2020/08/25 Python
激光脱毛、蓝光和护肤:Tria Beauty
2019/03/28 全球购物
实体的生命周期
2013/08/31 面试题
中西医结合临床医学专业大学生自荐信
2013/09/28 职场文书
鲜花方阵解说词
2014/02/13 职场文书
初三学习决心书
2014/03/11 职场文书
2014入党积极分子破除“四风”思想汇报
2014/09/14 职场文书
前台文员岗位职责
2015/02/04 职场文书
初三英语教学反思
2016/02/15 职场文书
MySQL高速缓存启动方法及参数详解(query_cache_size)
2021/07/01 MySQL