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 相关文章推荐
模拟SQLSERVER的两个函数:dateadd(),datediff()
Oct 09 PHP
新闻分类录入、显示系统
Oct 09 PHP
php在字符串中查找另一个字符串
Nov 19 PHP
PHP 批量删除 sql语句
Jun 05 PHP
php学习笔记(三)操作符与控制结构
Aug 06 PHP
那些年一起学习的PHP(三)
Mar 22 PHP
PHP面向对象学习笔记之二 生成对象的设计模式
Oct 06 PHP
php用ini_get获取php.ini里变量值的方法
Mar 04 PHP
php精确的统计在线人数的方法
Oct 21 PHP
Zend Framework入门教程之Zend_Registry组件用法详解
Dec 09 PHP
php实现的redis缓存类定义与使用方法示例
Aug 09 PHP
laravel Task Scheduling(任务调度)在windows下的使用详解
Oct 22 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
dede全站URL静态化改造[070414更正]
2007/04/17 PHP
PHP时间戳与日期之间转换的实例介绍
2013/04/19 PHP
php版微信开发之接收消息,自动判断及回复相应消息的方法
2016/09/23 PHP
Laravel5框架添加自定义辅助函数的方法
2018/08/01 PHP
javascript 客户端验证上传图片的大小(兼容IE和火狐)
2009/08/15 Javascript
让IE8支持DOM 2(不用框架!)
2009/12/31 Javascript
老鱼 浅谈javascript面向对象编程
2010/03/04 Javascript
jQuery图片预加载 等比缩放实现代码
2011/10/04 Javascript
百度地图api应用标注地理位置信息(js版)
2013/02/01 Javascript
Node.js 异步编程之 Callback介绍(一)
2015/03/30 Javascript
浅谈JavaScript 浏览器对象
2016/06/03 Javascript
AngularJs concepts详解及示例代码
2016/09/01 Javascript
微信小程序使用navigateTo数据传递的实例
2017/09/26 Javascript
bootstrap下拉框动态赋值方法
2018/08/10 Javascript
jQuery实现参数自定义的文字跑马灯效果
2018/08/15 jQuery
Vuex mutitons和actions初使用详解
2019/03/04 Javascript
js常见遍历操作小结
2019/06/06 Javascript
vue实现直播间点赞飘心效果的示例代码
2019/09/20 Javascript
JavaScript实现滑动门效果
2020/01/18 Javascript
vue实现前端分页完整代码
2020/06/17 Javascript
JS sort方法基于数组对象属性值排序
2020/07/10 Javascript
vue data对象重新赋值无效(未更改)的解决方式
2020/07/24 Javascript
vue实现一个矩形标记区域(rectangle marker)的方法
2020/10/28 Javascript
Python环境变量设置方法
2016/08/28 Python
攻击者是如何将PHP Phar包伪装成图像以绕过文件类型检测的(推荐)
2018/10/11 Python
500行Python代码打造刷脸考勤系统
2019/06/03 Python
对Django 转发和重定向的实例详解
2019/08/06 Python
一文了解python 3 字符串格式化 F-string 用法
2020/03/04 Python
django ListView的使用 ListView中获取url中的参数值方式
2020/03/27 Python
pycharm 关闭search everywhere的解决操作
2021/01/15 Python
外贸学院会计专业应届生求职信
2013/11/14 职场文书
法语专业求职信
2014/07/20 职场文书
挂靠协议书
2015/01/27 职场文书
2016读书月活动心得体会
2016/01/14 职场文书
python基础之类属性和实例属性
2021/10/24 Python
拙作再改《我的收音机情缘》
2022/04/05 无线电