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("%.{$place}f", substr(sprintf("%." . ($place * 2) . "f", $data), 0, -2));
        if ($type == 2) return (float)sprintf("%.{$place}f", substr(sprintf("%." . ($place + 2) . "f", $data), 0, -2));
        if ($type == 3) return (float)sprintf("%.{$place}f", 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));
        }
    }
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值