1 | <?php |
||
2 | |||
3 | // +---------------------------------------------------------------------- |
||
4 | // | ThinkLibrary 6.0 for ThinkPhP 6.0 |
||
5 | // +---------------------------------------------------------------------- |
||
6 | // | 版权所有 2017~2020 [ https://www.dtapp.net ] |
||
7 | // +---------------------------------------------------------------------- |
||
8 | // | 官方网站: https://gitee.com/liguangchun/ThinkLibrary |
||
9 | // +---------------------------------------------------------------------- |
||
10 | // | 开源协议 ( https://mit-license.org ) |
||
11 | // +---------------------------------------------------------------------- |
||
12 | // | gitee 仓库地址 :https://gitee.com/liguangchun/ThinkLibrary |
||
13 | // | github 仓库地址 :https://github.com/GC0202/ThinkLibrary |
||
14 | // | Packagist 地址 :https://packagist.org/packages/liguangchun/think-library |
||
15 | // +---------------------------------------------------------------------- |
||
16 | |||
17 | declare (strict_types=1); |
||
18 | |||
19 | namespace DtApp\ThinkLibrary\helper; |
||
20 | |||
21 | use DtApp\ThinkLibrary\exception\DtaException; |
||
22 | |||
23 | /** |
||
24 | * XML管理类 |
||
25 | * @mixin Xmls |
||
26 | * @package DtApp\ThinkLibrary\helper |
||
27 | */ |
||
28 | class Xmls |
||
29 | { |
||
30 | /** |
||
31 | * 数组转换为xml |
||
32 | * @param array $values 数组 |
||
33 | * @return string |
||
34 | * @throws DtaException |
||
35 | */ |
||
36 | public function toXml(array $values): string |
||
37 | { |
||
38 | if (!is_array($values) || count($values) <= 0) { |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
39 | throw new DtaException('数组数据异常!'); |
||
40 | } |
||
41 | $xml = "<xml>"; |
||
42 | foreach ($values as $key => $val) { |
||
43 | if (is_array($val)) { |
||
44 | $xml .= "<" . $key . ">" . $this->toXml($val) . "</" . $key . ">"; |
||
45 | } else if (is_numeric($val)) { |
||
46 | $xml .= "<" . $key . ">" . $val . "</" . $key . ">"; |
||
47 | } else { |
||
48 | $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">"; |
||
49 | } |
||
50 | } |
||
51 | $xml .= "</xml>"; |
||
52 | return $xml; |
||
53 | } |
||
54 | |||
55 | /** |
||
56 | * 将XML转为array |
||
57 | * @param string $xml |
||
58 | * @return mixed |
||
59 | * @throws DtaException |
||
60 | */ |
||
61 | public function toArray(string $xml) |
||
62 | { |
||
63 | if (!$xml) { |
||
64 | throw new DtaException('xml数据异常!'); |
||
65 | } |
||
66 | libxml_disable_entity_loader(true); |
||
67 | return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); |
||
68 | } |
||
69 | } |
||
70 |