Skip to content

Commit c4faf97

Browse files
authored
Fix xml decode error bug
1 parent 6b13713 commit c4faf97

File tree

1 file changed

+13
-36
lines changed

1 file changed

+13
-36
lines changed

src/Xml.php

+13-36
Original file line numberDiff line numberDiff line change
@@ -3,49 +3,26 @@
33
class Xml {
44
private static function intoObject(SimpleXMLElement $data, array &$need_array, string $key) {
55
$s = $data->__toString();
6-
if (str_replace([
7-
' ',
8-
"\n",
9-
"\r",
10-
"\t"
11-
], '', $s) != '') {
6+
if (str_replace([' ', "\n", "\r", "\t"], '', $s) != '') {
127
return $s;
138
}
149
$result = new stdClass();
15-
$flag = 0; // 0表示没有儿子 1表示有多个同键名儿子 2表示有儿子
16-
$map = [];
10+
$empty = true;
1711
foreach ($data as $k => $v) {
18-
$child_need_to_be_array = in_array("$key.$k", $need_array);
19-
if ($child_need_to_be_array && ! isset($result->{$k})) {
20-
$result->{$k} = [];
21-
}
22-
23-
// 有两项相同健值,说明这里需要转换为数组
24-
if (! $child_need_to_be_array && $flag !== 1 && array_key_exists($k, $map)) {
25-
$flag = 1;
26-
$ob = $result->{$k};
27-
$result = new stdClass();
28-
$result->{$k} = [
29-
$ob
30-
];
31-
}
32-
if ($flag === 0) {
33-
$flag = 2;
34-
}
35-
$map[$k] = null;
36-
if ($child_need_to_be_array || $flag === 1) {
37-
$result->{$k}[] = self::intoObject($v, $need_array, "$key.$k");
38-
} else {
39-
$result->{$k} = self::intoObject($v, $need_array, "$key.$k");
40-
}
12+
$empty = false;
13+
$result->{$k} ??= [];
14+
$result->{$k}[] = self::intoObject($v, $need_array, "$key.$k");
4115
}
42-
unset($v);
43-
// 一个儿子都没有,说明本项为空
44-
if ($flag === 0) {
16+
if ($empty) {
4517
return null;
46-
} else {
47-
return $result;
4818
}
19+
20+
foreach ($result as $k => &$v)
21+
if (1 === count($v) && ! in_array("$key.$k", $need_array)) {
22+
$v = current($v);
23+
}
24+
unset($v);
25+
return $result;
4926
}
5027
public static function decodeAsObject(string $data, array $need_array = []): stdClass {
5128
$xml = simplexml_load_string($data);

0 commit comments

Comments
 (0)