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 相关文章推荐
smarty section简介与用法分析
Oct 03 PHP
php长字符串定义方法
Jul 12 PHP
PHP基础教程(php入门基础教程)一些code代码
Jan 06 PHP
PHP字符过滤函数去除字符串最后一个逗号(rtrim)
Mar 26 PHP
linux命令之调试工具strace的深入分析
Jun 03 PHP
php中注册器模式类用法实例分析
Nov 03 PHP
php实现处理输入转义字符的代码
Nov 08 PHP
PHP生成各种常见验证码和Ajax验证过程
Jan 10 PHP
基于thinkPHP框架实现留言板的方法
Oct 17 PHP
PHP严重致命错误处理:php Fatal error: Cannot redeclare class or function
Feb 05 PHP
PHP使用Redis长连接的方法详解
Feb 12 PHP
php xhprof使用实例详解
Apr 15 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 网页过期时间的控制代码
2009/06/29 PHP
php获取新浪微博数据API实例
2013/11/12 PHP
php解析xml提示Invalid byte 1 of 1-byte UTF-8 sequence错误的处理方法
2013/11/14 PHP
php魔法函数与魔法常量使用介绍
2017/07/23 PHP
PHP实现支持CURL字符串证书传输的方法
2019/03/23 PHP
HTML中事件触发列表与解说
2007/07/09 Javascript
Firefox outerHTML实现代码
2009/06/04 Javascript
Jquery选中或取消radio示例
2013/09/29 Javascript
JS判断移动端访问设备并加载对应CSS样式
2014/06/13 Javascript
javascript学习笔记(五)原型和原型链详解
2014/10/08 Javascript
JavaScript实现将UPC转换成ISBN的方法
2015/05/26 Javascript
jQuery实现按钮只点击一次后就取消点击事件绑定的方法
2015/06/26 Javascript
轻松学习jQuery插件EasyUI EasyUI实现拖动基本操作
2015/11/30 Javascript
微信小程序通过api接口将json数据展现到小程序示例
2017/01/20 Javascript
Vuejs 组件——props数据传递的实例代码
2017/03/07 Javascript
Servlet3.0与纯javascript通过Ajax交互的实例详解
2018/03/18 Javascript
使用axios请求时,发送formData请求的示例
2019/10/29 Javascript
vue 返回上一页,页面样式错乱的解决
2019/11/14 Javascript
在Uni中使用Vue的EventBus总线机制操作
2020/07/31 Javascript
vue项目接口域名动态获取操作
2020/08/13 Javascript
Vue看了就会的8个小技巧
2021/01/21 Vue.js
django启动uwsgi报错的解决方法
2018/04/08 Python
python 切换root 执行命令的方法
2019/01/19 Python
Python3安装Pillow与PIL的方法
2019/04/03 Python
Django网络框架之HelloDjango项目创建教程
2019/06/06 Python
python图形用户接口实例详解
2019/12/16 Python
pytorch中使用cuda扩展的实现示例
2020/02/12 Python
Keras: model实现固定部分layer,训练部分layer操作
2020/06/28 Python
世界上最大的各式箱包网络零售店:eBag
2016/07/21 全球购物
英国最受欢迎的母婴精品品牌:JoJo Maman BéBé
2021/02/17 全球购物
Java的for语句中break, continue和return的区别
2013/12/19 面试题
标记环介质访问控制协议
2016/03/27 面试题
艺术专业大学生自我评价
2013/09/22 职场文书
井冈山红色之旅感想
2014/10/07 职场文书
学生喝酒检讨书500字
2014/11/02 职场文书
SpringBoot详解执行过程
2022/07/15 Java/Android