zoukankan      html  css  js  c++  java
  • array与xml转换实现(转)

        <?php
        function xml_encode($data, $charset = 'utf-8', $root = 'so') {
            $xml = '<?xml version="1.0" encoding="' . $charset .'"?>';
            $xml .= "<{$root}>";
            $xml .= array_to_xml($data);   
            $xml .= "</{$root}>";
            return $xml;
        }
    
        function xml_decode($xml, $root = 'so') {
            $search = '/<(' . $root . ')>(.*)</s*?\1s*?>/s';
            $array = array();
            if(preg_match($search, $xml, $matches)){
                $array = xml_to_array($matches[2]);
            }
            return $array;
        }
    
        function array_to_xml($array) {
            if(is_object($array)){
                $array = get_object_vars($array);
            }
            $xml = '';
            foreach($array as $key => $value){
                $_tag = $key;
                $_id = null;
                if(is_numeric($key)){
                    $_tag = 'item';
                    $_id = ' id="' . $key . '"';
                }
                $xml .= "<{$_tag}{$_id}>";
                $xml .= (is_array($value) || is_object($value)) ? array_to_xml($value) : htmlentities($value);
                $xml .= "</{$_tag}>";
            }
            return $xml;
        }
    
        function xml_to_array($xml) {
            $search = '/<(w+)s*?(?:[^/>]*)s*(?:/>|>(.*?)</s*?\1s*?>)/s';
            $array = array ();
            if(preg_match_all($search, $xml, $matches)){
                foreach ($matches[1] as $i => $key) {
                    $value = $matches[2][$i];
                    if(preg_match_all($search, $value, $_matches)){
                        $array[$key] = xml_to_array($value);
                    }else{
                        if('ITEM' == strtoupper($key)){
                            $array[] = html_entity_decode($value);
                        }else{
                            $array[$key] = html_entity_decode($value);
                        }
                    }
                }
            }
            return $array;
        }
    
  • 相关阅读:
    202002知识点
    爬取思想流程
    测试
    运维
    设计模式重温
    ?March2020疑问点
    最方便简洁的设置Sublime编辑预览MarkDown
    rime中州韵输入法安装及配置
    Deepin更新Sublime并取消更新提示
    关于在线教学软件一些发现和思考
  • 原文地址:https://www.cnblogs.com/chenqionghe/p/4379620.html
Copyright © 2011-2022 走看看