HiboxParseTool.class.php
2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?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;
}
}
?>