1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Class Xml |
4
|
|
|
* |
5
|
|
|
* @link https://www.icy2003.com/ |
6
|
|
|
* @author icy2003 <[email protected]> |
7
|
|
|
* @copyright Copyright (c) 2017, icy2003 |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace icy2003\php\ihelpers; |
11
|
|
|
|
12
|
|
|
use icy2003\php\I; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Xml 类 |
16
|
|
|
*/ |
17
|
|
|
class Xml |
18
|
|
|
{ |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* 判断字符串是否是 Xml |
22
|
|
|
* |
23
|
|
|
* @param string $xmlString |
24
|
|
|
* |
25
|
|
|
* @return bool |
26
|
|
|
*/ |
27
|
2 |
|
public static function isXml($xmlString) |
28
|
|
|
{ |
29
|
2 |
|
return false !== simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOERROR); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Xml 转成数组 |
34
|
|
|
* |
35
|
|
|
* 失败时返回空数组 |
36
|
|
|
* |
37
|
|
|
* @param string $xmlString Xml 字符串 |
38
|
|
|
* |
39
|
|
|
* @return array |
40
|
|
|
*/ |
41
|
1 |
|
public static function toArray($xmlString) |
42
|
|
|
{ |
43
|
1 |
|
if (false === self::isXml($xmlString)) { |
44
|
1 |
|
return []; |
45
|
|
|
} |
46
|
1 |
|
$isDisabled = libxml_disable_entity_loader(true); |
47
|
1 |
|
$xml = simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOCDATA); |
48
|
1 |
|
$array = Json::decode(Json::encode($xml), true); |
49
|
1 |
|
libxml_disable_entity_loader($isDisabled); |
50
|
1 |
|
return $array; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* 数组转成 Xml 字符串 |
55
|
|
|
* |
56
|
|
|
* @param array $array 数组 |
57
|
|
|
* @param bool $isRoot 是否带上根节点,默认 true |
58
|
|
|
* |
59
|
|
|
* @return string |
60
|
|
|
*/ |
61
|
1 |
|
public static function fromArray($array, $isRoot = true) |
62
|
|
|
{ |
63
|
1 |
|
$xmlstring = ''; |
64
|
1 |
|
true === $isRoot && $xmlstring .= '<xml>'; |
65
|
1 |
|
foreach ($array as $key => $value) { |
66
|
1 |
|
if (is_array($value)) { |
67
|
1 |
|
$subXmlString = self::fromArray($value, false); |
68
|
1 |
|
$xmlstring .= '<' . $key . '>' . $subXmlString . '</' . $key . '>'; |
69
|
|
|
} else { |
70
|
1 |
|
if (is_numeric($value)) { |
71
|
1 |
|
$xmlstring .= '<' . $key . '>' . $value . '</' . $key . '>'; |
72
|
|
|
} else { |
73
|
1 |
|
$xmlstring .= '<' . $key . '><![CDATA[' . $value . ']]></' . $key . '>'; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
1 |
|
true === $isRoot && $xmlstring .= '</xml>'; |
78
|
1 |
|
return $xmlstring; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|