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

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

(0)

相关推荐

  • 分享php代码将360浏览器导出的favdb的sqlite数据库文件转换为html

    下面给大家分享了一段php代码,讲解将360浏览器导出的favdb的sqlite数据库文件转换为html,下面代码简单易懂,感兴趣的朋友看一下吧. php代码如下所示: <?php $book_mark_name = 'book_mark.html'; $content = file_get_contents('tb_fav.json'); var_dump($content); $content_list = json_decode($content,'utf-8'); $content_li

  • php将数组转换成csv格式文件输出的方法

    本文实例讲述了php将数组转换成csv格式文件输出的方法.分享给大家供大家参考.具体实现方法如下: <?php $sales = array( array('east','2005-01-01','2005-02-01',12.54), array('west','2005-01-01','2005-02-01',546.33), array('south','2005-01-01','2005-02-01',93.26), array('north','2005-01-01','2005-02

  • PHP将HTML转换成文本的实现代码

    核心代码: <?php // $document 应包含一个 HTML 文档. // 本例将去掉 HTML 标记,javascript 代码 // 和空白字符.还会将一些通用的 // HTML 实体转换成相应的文本. $search = array ("'<script[^>]*?>.*?</script>'si", // 去掉 javascript "'<[\/\!]*?[^<>]*?>'si", //

  • PHP+Mysql日期时间如何转换(UNIX时间戳和格式化日期)

    写过PHP+MySQL的程序员都知道有时间差,UNIX时间戳和格式化日期是我们常打交道的两个时间表示形式,Unix时间戳存储.处理方便,但是不直观,格式化日期直观,但是处理起来不如Unix时间戳那么自如,所以有的时候需要互相转换,下面给出互相转换的几种转换方式. 一.在MySQL中完成 这种方式在MySQL查询语句中转换,优点是不占用PHP解析器的解析时间,速度快,缺点是只能用在数据库查询中,有局限性. 1. UNIX时间戳转换为日期用函数: FROM_UNIXTIME() 一般形式:selec

  • 使用PHP+JavaScript将HTML页面转换为图片的实例分享

    1,准备要素 1)替换字体的js文件 js代码: function com_stewartspeak_replacement() { /* Dynamic Heading Generator By Stewart Rosenberger http://www.stewartspeak.com/headings/ This script searches through a web page for specific or general elements and replaces them wi

  • php将日期格式转换成xx天前的格式

    本文实例讲述了php将日期格式转换成xx天前格式的方法.分享给大家供大家参考.具体如下: 这段代码可以把时间格式化成3天前,5秒前,2年前的形式 // convert a date into a string that tells how long ago // that date was.... eg: 2 days ago, 3 minutes ago. function ago($d) { $c = getdate(); $p = array('year', 'mon', 'mday',

  • php颜色转换函数hex-rgb(将十六进制格式转成十进制格式)

    复制代码 代码如下: <?php    function hex2rgb($colour) {       if ($colour [0] == '#') {           $colour = substr ( $colour, 1 );       }       if (strlen ( $colour ) == 6) {           list ( $r, $g, $b ) = array ($colour [0] . $colour [1], $colour [2] . $c

  • PHP转换文本框内容为HTML格式的方法

    本文实例讲述了PHP转换文本框内容为HTML格式的方法.分享给大家供大家参考,具体如下: 有时候我们将会用到将多行文本框中输入的内容以html格式显示出来,这样子可以保持原来的文本格式,如换行.回车等.可以通过下面的函数实现: function shtm($design_str) { $str=trim($design_str); // 取得字串同时去掉头尾空格和空回车 //$str=str_replace("<br>","",$str); // 去掉&

  • php导出csv格式数据并将数字转换成文本的思路以及代码分享

    php导出csv格式数据实现:先定义一个字符串 存储内容,例如 $exportdata = '规则111,规则222,审222,规222,服2222,规则1,规则2,规则3,匹配字符,设置时间,有效期'."\n"; 然后对需要保存csv的数组进行foreach循环,例如 复制代码 代码如下: if (!empty($lists)){                  foreach($lists as $key => $value){                    $ti

  • php中将html中的br换行符转换为文本输入中的换行符

    下面这几个方法将能够帮你解决这个问题. PHP版将html中的<br />换行符转换为文本框中的换行符: 复制代码 代码如下: function br2nl($text){    return preg_replace('/<br\\s*?\/??>/i','',$text);} 或者: 复制代码 代码如下: function br2nl($text){    $text=preg_replace('/<br\\s*?\/??>/i',chr(13),$text); r

随机推荐