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配置文件中最常用四个ini函数
Mar 19 PHP
php面向对象全攻略 (四)构造方法与析构方法
Sep 30 PHP
PHP统计目录下的文件总数及代码行数(去除注释及空行)
Jan 17 PHP
三个类概括PHP的五种设计模式
Sep 05 PHP
简单实现限定phpmyadmin访问ip的方法
Mar 05 PHP
关于Iframe如何跨域访问Cookie和Session的解决方法
Apr 15 PHP
简述php环境搭建与配置
Dec 05 PHP
PHP中file_put_contents追加和换行的实现方法
Apr 01 PHP
Yii2 如何在modules中添加验证码的方法
Jun 19 PHP
PHP preg_match实现正则表达式匹配功能【输出是否匹配及匹配值】
Jul 19 PHP
Laravel 自定命令以及生成文件的例子
Oct 23 PHP
phpstudy后门rce批量利用脚本的实现
Dec 12 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
Javascript - HTML的request类
2007/01/09 Javascript
jquery中防刷IP流量软件影响统计的一点对策
2011/07/10 Javascript
用JQUERY增删元素的代码
2012/02/14 Javascript
jQuery学习笔记 更改jQuery对象
2012/09/19 Javascript
使用JavaScript的ActiveXObject对象检测应用程序是否安装的方法
2014/04/15 Javascript
JQuery 给元素绑定click事件多次执行的解决方法
2014/09/09 Javascript
原生javascript实现简单的datagrid数据表格
2015/01/02 Javascript
基于jQuery实现动态数字展示效果
2015/08/12 Javascript
javascript实现dom元素可拖动
2016/03/21 Javascript
简单谈谈JS数组中的indexOf方法
2016/10/13 Javascript
easyui datagrid 大数据加载效率慢,优化解决方法(推荐)
2016/11/09 Javascript
关于JavaScript中的this指向问题总结篇
2017/07/23 Javascript
基于js 各种排序方法和sort方法的区别(详解)
2018/01/03 Javascript
Angularjs实现多图片上传预览功能
2018/07/18 Javascript
详解如何使用微信小程序云函数发送短信验证码
2019/03/13 Javascript
微信小程序如何访问公众号文章
2019/07/08 Javascript
JS实现移动端在线签协议功能
2019/08/22 Javascript
[15:07]lgd_OG_m2_BP
2019/09/10 DOTA
python模拟登录百度贴吧(百度贴吧登录)实例
2013/12/18 Python
用Python编写一个国际象棋AI程序
2014/11/28 Python
python绘制直线的方法
2018/06/30 Python
python实现控制电脑鼠标和键盘,登录QQ的方法示例
2019/07/06 Python
Python 获取windows桌面路径的5种方法小结
2019/07/15 Python
django实现将修改好的新模型写入数据库
2020/03/31 Python
Python用类实现扑克牌发牌的示例代码
2020/06/01 Python
介绍CSS3使用技巧5个
2009/04/02 HTML / CSS
Boden美国官网:英伦原创时装品牌
2017/07/03 全球购物
英国网络托管和域名领导者:Web Hosting UK
2017/10/15 全球购物
英国女装网上商店:I Saw It First
2018/10/18 全球购物
Abbott Lyon官网:女士手表、珠宝及配件
2020/12/26 全球购物
关于对大人不礼貌的检讨书
2014/09/29 职场文书
教师政风行风评议心得体会
2014/10/21 职场文书
小升初自荐信范文
2015/03/05 职场文书
预备党员考察意见范文
2015/06/01 职场文书
《领导干部从政道德启示录》学习心得体会
2016/01/20 职场文书
详解Redis在SpringBoot工程中的综合应用
2021/10/16 Redis