HiboxParseTool.class.php 2.95 KB
<?php
/**
 * Hibox抽象类---解析开放接口响应内容(Object)格式为 XML或JSON格式
 * @see api.hibox.com/hop1/include/Application.class.php
 */
abstract class HiboxParseTool 
{
    /**
     * 解析对象转换为XML格式
     * 
     * @param object $obj
     * @param string $nodeBlock
     * @param string $nodeName
     */
    public static function parseObjToXml( $obj, $nodeBlock = 'hibox', $nodeName = 'node' ) 
    {
        $array = self::mapGetObjVars( $obj );
        return self::parseArrayToXml( $array, $nodeBlock, $nodeName );
    }
    
    /**
     * 解析数组转换XML
     * 
     * @param array $array
     * @param string $nodeBlock
     * @param string $nodeName
     */
    public static function parseArrayToXml( $array, $nodeBlock = 'hibox', $nodeName = 'node' ) 
    {
        $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . PHP_EOL;

        $xml .= '<' . $nodeBlock . '>' . PHP_EOL;
        $xml .= self::genArrayToXml( $array, $nodeName );
        $xml .= '</' . $nodeBlock . '>';

        return $xml;
    }
    
    /**
     * 解析对象转换为JSON格式
     * @param object $obj
     * @return string
     */
    public static function parseObjToJson( $obj )
    {
        return json_encode( $obj );
    }

    /**
     * 递归回调方式将数组转换为XML
     * @param array $array
     * @param string $nodeName
     */
    private static function genArrayToXml( $array, $nodeName ) 
    {
        $xml = '';

        if ( is_array( $array ) && count( $array ) > 0 ) 
        {
            foreach ( $array as $key => $value) 
            {
                if ( is_numeric( $key ) ) 
                {
                    $key = $nodeName;
                }

                $xml .= '<' . $key . '>' . self::genArrayToXml( $value, $nodeName ) . '</' . $key . '>' . PHP_EOL;
            }
        } 
        else 
        {
            if ( is_string( $array ) )
            {
                $xml = htmlspecialchars( $array, ENT_QUOTES );
            }
        }

        return $xml;
    }
    
    /**
     * 递归回调方式将对象转换为数组
     * @param mixed (array | object)
     * @return array
     */
    private static function mapGetObjVars( $data )
    {
        $array = array();
        if ( is_object( $data ) )
        {
            $array = get_object_vars( $data );
            foreach ( $array as $key => $section )
            {
                if ( is_object( $section ) )
                {
                    $array[ $key ] = self::mapGetObjVars( $section );
                }
                // 嵌套递归 案例: 对象Response> 对象 data >> 数组 >>> 对象
                else if ( is_array( $section) && count($section) )
                {
                    foreach ( $section as $subKey => $subSection )
                    {
                        $array[ $key ][ $subKey ] = self::mapGetObjVars( $subSection );
                    }
                }
            }
        }
        return $array;
    }
}
?>