要获得一系列父母/孩子,您可以使用:
<?php
$content = file_get_contents('http://www.fluffyduck.com.au/sampleXML.txt');
$xml = new SimpleXMLElement($content);
$users = array ();
myUserReader($xml->user, $users);
function myUserReader($node, &$users)
{
if (array_key_exists("{$node['id']}", $users) === false)
{
$users["{$node['id']}"] = array ();
}
if (isset($node->user))
{
for ($key = 0; ($key < $node->user->count()); $key++)
{
$user = $node->user[$key];
if (!in_array("{$node['id']}", $users["{$node['id']}"]))
{
$users["{$node['id']}"][] = "{$user['id']}";
}
myUserReader($user, $users);
}
}
}
foreach ($users as $parent => $children)
{
echo "{$parent}: " . implode(", ", $children) . "\n";
}
?>
这将输出:
41: 61, 62, 69, 89, 127, 204, 323, 340, 341
61:
62: 64, 78, 80, 116, 120
64: 66
66: 67
67: 68, 114, 161, 162, 166, 203
68: 70
70: 72, 77, 104, 118, 135, 138, 143, 154, 156, 171, 172, 173, 174
72: 73, 86, 163, 165, 167
73: 75
75:
86: 92, 103, 108, 112, 117, 119, 121, 124, 125, 137, 144
92: 107, 110, 111, 142
107:
110:
111:
142:
103:
108:
112:
117:
119:
121:
124:
125:
137:
144:
163:
165:
167:
77: 79, 113
79:
113:
104: 106
106:
118:
135:
138:
143:
154:
156:
171:
172:
173:
174:
114:
161:
162:
166: 169, 175, 176, 178, 179, 180, 183, 184, 205, 206
169:
175:
176:
178:
179:
180:
183:
184:
205:
206:
203:
78: 136
136:
80: 101
101:
116: 122, 126, 129, 130, 131, 133, 139, 140, 141
122:
126:
129:
130:
131:
133:
139:
140:
141:
120: 145, 146, 147, 148, 149, 150, 151, 157, 160, 168
145:
146:
147:
148:
149:
150: 152, 153, 155, 159
152:
153:
155:
159:
151:
157:
160:
168:
69:
89:
127:
204: 207
207: 208, 209, 210, 211, 212, 227, 254, 300
208: 213, 214, 215, 226, 228, 234, 255, 294, 295, 297, 299, 320
213:
214:
215:
226:
228:
234:
255: 274, 275
274:
275:
294:
295:
297:
299:
320:
209:
210: 217, 218, 222
217:
218:
222:
211:
212:
227:
254:
300:
323:
340:
341: