php xml 和json转成Array(数组)格式和数组转成xml和json

Posted 哈尔滨洛弘科技有限公司

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php xml 和json转成Array(数组)格式和数组转成xml和json相关的知识,希望对你有一定的参考价值。

直接复制代码使用,非常nice

<?php
/**
 * Class Datatype
 * @package rely\\init
 * @author Mr.taochuang <mr_taochuang@163.com>
 * @date 2019/7/3 12:32
 * 数据操作类
 */
class Dataswitch

    /**
     * @var
     * 错误信息
     */
    public $message = '';

    /**
     *支持所有字符均可变成数组
     * @param $data /要转换的数据
     * @param null $partition 字符串炸开数组分隔符
     * @return array|mixed|string
     * 转数组
     */
    public function toArray($data, $partition = null)
    
        $data_type = self::getDataType($data);
        if ($data_type == 'array') return $data;
        if ($data_type == 'json') return self::json2array($data);
        if ($data_type == 'xml') return self::xml2array($data);
        if (!is_null($partition) && $data_type == 'string') return explode($partition, $data);
        if ($data_type = 'object') return self::object2array($data);
        $this->message = '数据格式不正确转换出错';
        return $data;
    

    /**
     * 支持所有字符均可变成json
     * @param $data /要转的数据
     * @return array|mixed|string
     * 转json
     */
    public function toJson($data)
    
        $data_type = self::getDataType($data);
        if ($data_type == 'json') return $data;
        $data = self::toArray($data);
        if (is_array($data)) 
            return preg_replace_callback('/\\\\\\\\u([0-9a-f]4)/i', function ($matches) 
                return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");
            , ($jsonData = json_encode($data)) == '[]' ? '' : $jsonData);
         else 
            $this->message = '数据格式不正确转换出错';
            return $data;
        
    

    /**
     *支持所有字符均可变成xml
     * @param $data /要转的数据
     * @return array|mixed|string
     * 转xml
     */
    public function toXml($data)
    
        $data_type = self::getDataType($data);
        if ($data_type == 'xml') return $data;
        $data = self::toArray($data);
        if (is_array($data)) 
            return "<xml>" . self::arr2xml($data) . "</xml>";
         else 
            $this->message = '数据格式不正确转换出错';
            return $data;
        
    

    /**
     * @param $data /要转的数据
     * @return array|mixed|object|string
     * 转对象
     */
    public function toObject($data)
    
        $data_type = self::getDataType($data);
        if ($data_type == 'object') return $data;
        $data = self::toArray($data);
        return (object)$data;
    

    /**
     * @param $data /要转的数据
     * @param null $partition 分隔符
     * @return string
     * 转字符串
     */
    public function toString($data, $partition = null)
    
        $data_type = self::getDataType($data);
        if ($data_type == 'string') return $data;
        $data = self::toArray($data);
        return is_null($partition) ? implode('', $data) : implode($partition, $data);

    

    /**
     * @param $data /要转换的数字
     * @param int $place /保留几位小数
     * @param int $type /1四舍五入 2向下取 3向上取
     * @return float|int
     * 数字转换
     */
    public function toNumber($data, int $place = 2, int $type = 1)
    
        if (is_numeric($data) === false) return $data;
        if ($place == 0 && $type == 1) return (int)round($data);
        if ($place == 0 && $type == 2) return (int)floor($data);
        if ($place == 0 && $type == 3) return (int)ceil($data);
        if ($type == 1) return (float)sprintf("%.$placef", substr(sprintf("%." . ($place * 2) . "f", $data), 0, -2));
        if ($type == 2) return (float)sprintf("%.$placef", substr(sprintf("%." . ($place + 2) . "f", $data), 0, -2));
        if ($type == 3) return (float)sprintf("%.$placef", substr(sprintf("%." . ($place + 2) . "f", $data), 0, -2)) + (1 / (pow(10, $place)));
        return $data;
    

    /**
     * @param $data /json数据
     * @return mixed
     * @throws \\Exception
     * json转数组
     */
    public function json2array($data)
    
        $result = json_decode($data, true);
        if (empty($result)) 
            throw new \\Exception('invalid response.', '0');
        
        return $result;
    

    /**
     * @param $data /xml数据
     * @return mixed
     * xml转数组
     */
    public function xml2array($data)
    
        $entity = libxml_disable_entity_loader(true);
        $data = (array)simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        libxml_disable_entity_loader($entity);
        return json_decode(self::toJson($data), true);
    

    /**
     * @param $data /object对象
     * @return array
     * 对象转为数组
     */
    public function object2array($data)
    
        if (is_object($data)) 
            $data = (array)$data;
        
        if (is_array($data)) 
            foreach ($data as $key => $value) 
                $data[$key] = self::object2array($value);
            
        
        return $data;
    

    /**
     * XML内容生成
     * @param array $data 数据
     * @param string $content
     * @return string
     */
    private static function arr2xml($data, $content = '')
    
        foreach ($data as $key => $val) 
            is_numeric($key) && $key = 'item';
            $content .= "<$key>";
            if (is_array($val) || is_object($val)) 
                $content .= self::arr2xml($val);
             elseif (is_string($val)) 
                $content .= '<![CDATA[' . preg_replace("/[\\\\x00-\\\\x08\\\\x0b-\\\\x0c\\\\x0e-\\\\x1f]/", '', $val) . ']]>';
             else 
                $content .= $val;
            
            $content .= "</$key>";
        
        return $content;
    

    /**
     * @param $data
     * @param int $page_num
     * @param null $page
     * @return array
     * 数组分页
     */
    public function array_page(array $data, $page_num = 15, $page = null)
    
        if (is_null($page)) $page = $_REQUEST['page'];
        empty($page) ? $page = 1 : true;
        $data = array_slice($data, ($page - 1) * $page_num, $page_num);
        $total = count($data);
        return ['total' => $total, 'per_page' => $page_num, 'current_page' => $page, 'last_page' => ceil($total / $page_num), 'data' => $data];
    

    /**
     * @param $data
     * 获取数据类型
     */
    public function getDataType($data)
    
        $type = gettype($data);
        if ($type == 'string') 
            if ($this->json_check($data)) $type = 'json';
            if ($this->xml_check($data)) $type = 'xml';
        
        return $type;
    

    /**
     * @param $data
     * @return bool
     * 检测是否为json数据
     */
    public function json_check($data)
    
        if (!is_null(json_decode($data))) 
            return true;
         else 
            return false;
        
    

    /**
     * @param $data
     * @return bool|mixed
     * 检测是否为xml数据
     */
    public function xml_check($data)
    
        $xml_parser = xml_parser_create();
        if (!xml_parse($xml_parser, $data, true)) 
            xml_parser_free($xml_parser);
            return false;
         else 
            return (json_decode(json_encode(simplexml_load_string($data)), true));
        
    

以上是关于php xml 和json转成Array(数组)格式和数组转成xml和json的主要内容,如果未能解决你的问题,请参考以下文章

php xml 和json转成Array(数组)格式和数组转成xml和json

php十行代码将xml转成数组

PHP csv文件内容转成数组/Json

[PHP] xml转对象函数simplexml_load_string

PHP json_decode为什么将json字符串转成数组是对象格式?

XML 到 JSON 或数组? PHP