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

本文实例讲述了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程序设计有所帮助。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索xml
, php
, 转换
数据格式
dom解析xml实例、xml实例、webservice xml 实例、xml接口实例、java解析xml文件实例,以便于您获取更多的相关知识。

时间: 2024-12-21 22:53:10

PHP实现XML与数据格式进行转换类实例_php技巧的相关文章

PHP生成RSS文件类实例_php技巧

本文实例讲述了PHP生成RSS文件类文件.分享给大家供大家参考.具体如下: PHP RSS 生成类实例代码如下: 复制代码 代码如下: <?php if (defined('_class_rss_php')) return; define('_class_rss_php教程',1); /**    *  使用说明:  *  $rss = new rss('redfox','http://jb51.net/',"redfox's blog");  *  $rss->addit

php将图片保存为不同尺寸图片的图片类实例_php技巧

本文实例讲述了php将图片保存为不同规格的图片类.分享给大家供大家参考.具体如下: 图片处理类.imagecls.php如下: <?php /** 图片处理类 */ class imagecls { /** * 文件信息 */ var $file = array(); /** * 保存目录 */ var $dir = ''; /** * 错误代码 */ var $error_code = 0; /** * 文件上传最大KB */ var $max_size = -1; function es_i

简单实用的网站PHP缓存类实例_php技巧

缓存技术在实际使用当中应用非常广泛,可以有效减轻对服务器数据库的访问压力,提高运行速度.目前很多CMS内容管理系统中频繁使用缓存机制来提高系统运行的效率.本文以一个简单实用的缓存类为例,帮助大家参考下缓存的机制与写法. 缓存文件cache.php代码如下: <?php /* 用户需要事先定义的常量: _CachePath_ 模板缓存路径 _CacheEnable_ 自动缓存机制是否开启,未定义或为空,表示关闭自动缓存机制 _ReCacheTime_ 自动重新缓存间隔时间,单位为秒,未定义或为空,

php的mssql数据库连接类实例_php技巧

本文实例讲述了php的mssql数据库连接类实例代码,分享给大家供大家参考. 具体实现代码如下: 复制代码 代码如下: class DB_Sql {   var $Host     = "";   var $Database = "";   var $User     = "";   var $Password = "";   var $Link_ID  = 0;   var $Query_ID = 0;   var $Rec

php实现用于计算执行时间的类实例_php技巧

本文实例讲述了php实现用于计算执行时间的类.分享给大家供大家参考.具体如下: 有了这个php类,计算函数或者一段代码的执行时间就简单了 <?php class c_Timer { var $t_start = 0; var $t_stop = 0; var $t_elapsed = 0; function start() { $this->t_start = microtime(); } function stop() { $this->t_stop = microtime(); }

PHP实现阳历到农历转换的类实例_php技巧

本文实例讲述了PHP实现阳历到农历转换的类.分享给大家供大家参考.具体如下: 复制代码 代码如下: <?php //PHP阳历到农历转换的一个类 class Calendar { //农历每月的天数     var $everyCMonth=array(     0=>array(8,0,0,0,0,0,0,0,0,0,0,0,29,30,7,1),     1=>array(0,29,30,29,29,30,29,30,29,30,30,30,29,0,8,2),     2=>

php 中英文语言转换类代码_php技巧

起初想到制成XML文档形式,这样操作也起来很容易.只是看到说XML效率不怎样 再者就是不同的模板,可这样也有个小问题,有些词汇比如时间提示是不确定,与可能是minute ,day.也有可能复数加 s 那好吧,做成数组,可数组就得做成在php文件的变量,很难做些扩展(我所知道所认为的是这样) 最后做成txt文本文件的形式,同样也为这样的效率担心,打开文件,搜索字符串,截取字符串这些,所幸最后运行了一下,一般机子大概0.0004秒,这让我很惊奇原以为会很慢,毕竟要调用多次. 好吧,上代码 复制代码

php导出中文内容excel文件类实例_php技巧

本文实例讲述了php导出中文内容excel文件类.分享给大家供大家参考.具体如下: <?php class toExcel{ public $link = null; function __construct(){ } /*************************************************************************** * $mapping:数组格式头信息$map=array('No','Name','Email','Age'); * $dat

微信公众号开发之微信公共平台消息回复类实例_php技巧

本文实例讲述了微信公众号开发之微信公共平台消息回复类.分享给大家供大家参考.具体如下: 微信公众号开发代码我在网上看到了有不少,其实都是大同小义了都是参考官方给出的demo文件进行修改的,这里就给各位分享一个. 复制代码 代码如下: <?php /**  * 微信公共平台消息回复类  *  *  */ class BBCweixin{    private $APPID="******";  private $APPSECRET="******";  /*